forward:hello 与 redirect:hello的区别

本文介绍了Spring MVC中两种常用视图返回方式:转发(forward)与重定向(redirect)。通过示例展示了如何使用这两种方法,并解释了它们之间的区别:转发保持原URL不变并在同一请求上下文中处理,而重定向则会改变URL并发起新的请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于某些Controller的处理方法,当返回值为String类型时,返回的结果中可能含有forward或redirect前缀;

如:

@Controller
@RequestMapping("/user")
public class UserController {
	@RequestMapping("/forward")
	public String replyWithForward(HttpServletRequest request, String userId){
		request.setAttribute("userid", userId);
		
		System.out.println("userId =" +userId);
		
		return "forward:hello";
	}
	
	@RequestMapping("/redirect")
	public String replyWithRedirect(HttpServletRequest request, String userId){
		request.setAttribute("userid", userId);
		
		System.out.println("userId = "+userId);
		
		return "redirect:hello";
	}
}

 测试页面hello.jsp;

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
 	String userId = (String)request.getAttribute("userid");   
 	System.out.println("获取到的userId为:"+userId);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试页面</title>
</head>
<body>
	hello, <%= userId %>;
</body>
</html>

 当路径为 http://localhost:8080/crazysnailweb/user/forward?userId=123时,浏览器中的URL不会发生变化,且页面输出:

      

 当路径为http://localhost:8080/crazysnailweb/user/redirect?userId=123 时,浏览器中URL变为http://localhost:8080/crazysnailweb/user/hello,且页面输出:

      

注:redirect会让浏览器发起一个新的请求,因而原来request对象中的参数丢失;而forward所到的目标地址位于当前请求中,request中的参数不会丢失;
 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值