forward:hello 与 redirect:hello的区别

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

如:

Usercontroller代码   收藏代码
  1. @Controller  
  2. @RequestMapping("/user")  
  3. public class UserController {  
  4.     @RequestMapping("/forward")  
  5.     public String replyWithForward(HttpServletRequest request, String userId){  
  6.         request.setAttribute("userid", userId);  
  7.           
  8.         System.out.println("userId =" +userId);  
  9.           
  10.         return "forward:hello";  
  11.     }  
  12.       
  13.     @RequestMapping("/redirect")  
  14.     public String replyWithRedirect(HttpServletRequest request, String userId){  
  15.         request.setAttribute("userid", userId);  
  16.           
  17.         System.out.println("userId = "+userId);  
  18.           
  19.         return "redirect:hello";  
  20.     }  
  21. }  

 测试页面hello.jsp;

Html代码   收藏代码
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%  
  4.     String userId = (String)request.getAttribute("userid");     
  5.     System.out.println("获取到的userId为:"+userId);  
  6. %>  
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  8. <html>  
  9. <head>  
  10. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  11. <title>测试页面</title>  
  12. </head>  
  13. <body>  
  14.     hello, <%= userId %>;  
  15. </body>  
  16. </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中的参数不会丢失;


参考:http://blog.youkuaiyun.com/jackpk/article/details/19121777

http://dufengx201406163237.iteye.com/blog/2097416

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值