SpringMVC重定向和转发重定向和转发 重定向经过客户端,而转发没有,因此相对来说转发更快速。但有时采用重定向更方便,如:重定向到外部网站;避免用户重新加载页面时再次调用同样的动作。returnredirect:viewsaveUser。getId(); 这里使用重定向来防止当前用户重新加载页面时saveUser被二次调用。 但是使用重定向无法轻松地给目标页面传值,因此,在Spring3。1后提供了Flash属性,详情见后文。常用处理方式 Controller视图方法间的跳转,无非就是带参跳转和不带参跳转。常用的方法有通过String映射RequestMapping实现重定向,或者通过ModelAndView对象,又或者是RedirectView对象,下面逐一说明。String重定向 是return映射到另一个Controller方法的字符串。如果有请求参数,就拼接在RequestMapping映射的字符串后面。返回字符串映射的方式RequestMapping(hello)publicStringhello(HttpServletRequestreq,HttpServletResponseresp){doSomething();returnredirect:bye;returnredirect:bye?usernamesudoz;}ModelAndView重定向 另一种方法是通过返回ModelAndView对象来实现跳转。类似的,如果有请求参数,也可以通过类似GET参数拼接的方式:返回ModelAndView对象RequestMapping(hello)publicModelAndViewhello(HttpServletRequestreq,HttpServletResponseresp){doSomething();returnnewModelAndView(redirect:bye);returnnewModelAndView(redirect:bye?usernamesudoz);}RedirectView重定向 还有一种方法是通过返回RedirectView对象实现跳转,该方法和上面的不同之处在于,RedirectView对象不需要设置redirect前缀:返回RedirectView对象RequestMapping(hello)publicRedirectViewhello(){doSomething();returnnewRedirectView(bye);returnnewRedirectView(bye?usernamesudoz);} 带参跳转 Model在重定向时会丢失携带的消息 在做方法跳转时,如果要把参数带给下一个方法,像上面代码里通过拼接URL参数的方法有时候并不实用。因为参数不一定都是是字符串,而且浏览器对URL的长度是有限制的。RedirectAttributes对象可以用来保存请求重定向时的参数。利用RedirectAttributes改写上面的代码:RequestMapping()publicRedirectViewhello(RedirectAttributesattrs){attrs。addAttribute(message,hello);attrs。addFlashAttribute(username,world);returnnewRedirectView(hello);}RequestMapping(hello)MapString,Stringhello(ModelAttribute(message)Stringmeaasge,ModelAttribute(username)Stringusername){MapString,StringmapnewHashMap();map。put(message,message);map。put(username,username);returnmap;} 上面的代码中,调用addAttribute()和addFlashAttribute()方法往RedirectAttributes对象中插入了两个值,如果看源码,就能知道,RedirectAttributes接口的实现类RedirectAttributesModelMap继承了ModelMap,本质上就是HashMap的子类,因此可以用来存储KeyValue对。这两个方法都很常用,使用上也必然存在不同:addAttribute()方法会把KeyValue作为请求参数添加的URL的后面;addFlashAttribute()方法会把KeyValue暂存在session中,在跳转到目标方法后,即完成任务,会从session中删掉; 用curl命令来测试:curlihttp:localhost:8080HTTP1。1302SetCookie:JSESSIONIDD1CC5E15FA8EF9474C4CED7D4F660E66;path;HttpOnlyLocation:http:localhost:8080hello;jsessionidD1CC5E15FA8EF9474C4CED7D4F660E66?usernamesudozContentLanguage:enUSContentLength:0Date:Thu,16Feb201712:33:46GMT 可以看到,通过addAttribute()添加的键值对变成了URL后面的参数,addFlashAttribute()方法添加的键值对则没有出现在URL上,而是存储在了session中。跳转的目标方法通过ModelAttribute(key)注解指定接收的参数。 redirect和forward的区别 上面列出的3种方法,其实都是SpringMVC在处理请求时的重定向,即redirect跳转。另一种分发请求的方式是转发,即forward。二者的区别从HTTP的规范中就明确:redirect的HTTP返回码是302,且跳转的新URL会存储在HTTPResponseHeaders的Location字段中。客户端在接收到Response后,会发起另一次请求,这次请求的URL就是重定向的URL;forward的转发过程只发生在服务端;Servlet容器会直接把源请求打向目标URL,而不会经由客户端发起请求;因此客户端接收到的响应是来自转发后的目标方法,但是浏览器呈现的URL却并不会改变,且forward不能将参数转发出去。