SpringMVC Controller间跳转,需重定向。session
分三种状况:(1)不带参数跳转(2)带参数拼接url形式跳转(3)带参数不拼接参数跳转,页面也能显示。url
一、不带参数重定向get
需求案例:在列表页面,执行新增操做,新增在后台完成以后要跳转到列表页面,不须要传递参数,列表页面默认查询全部项目。flash
(1)方式一:使用ModelAndView(这是Spring 2.0用到的方法)io
return new ModelAndView("redirect:/toList");test
这样能够重定向到toList这个方法。后台
(2)方式二:返回String乱码
return "redirect:/toList";表单
二、带参数重定向List
需求案例:在列表页面有查询条件,跳转后查询条件不能丢,这样就须要带参数。
(1)方式一:本身手动拼接url
new ModelAndView("redirect:/toList?param1="+value1+"¶m2="+value2);
这样有个弊端,就是传中文可能有乱码问题。
(2)方式二:用RedirectAttributes,调用addAttribute方法,url会自动拼接参数。
public String test(RedirectAttributes attributes){
attributes.addAttribute("test","hello");
return "redirect:/test/test2";
}
这样在test2方法中就能够经过得到参数的方式得到这个参数,再传递到页面。此种方式也会有中文乱码的问题。
(3)方式三:用RedirectAttributes,调用addFlashAttribute方法,url会自动拼接参数。
public String red(RedirectAttributes attributes){
attributes.addFlashAttribute("test","hello");
return "redirect:/test/test2";
}
用上边的方式进行数据传递,不会在url出现要传递的数据,实际上存储在flashmap中。
FlashAttribute和RedirectAttribute:经过FlashMap存储一个请求的输出,当进入另外一个请求时做为该请求的输入。典型场景如重定向(POST-REDIRECT-GET模式,一、POST时将下一次须要的数据放在FlashMap;二、重定向;三、经过GET访问重定向的地址,此时FlashMap会把1放到FlashMap的数据取出来放到请求中,并从FlashMap中删除;从而支持在两次请求之间保存数据并防止了重复表单提交)
SpringMVC提供FlashMapManager用于管理FlashMap,默认使用SessionFlashMapManager,即数据默认存储在session中。有两种方式把addFlashAttribute中的数据提取出来。
方法一:利用HttpServletRequest
public String test2(HttpServletRequest request){
Map<String,?> map = RequestContextUtils.getInputFlashMap(request);
System.out.println(map.get("test").toString());
return "/test/hello";
}
方法二:利用Spring提供的标签@ModelAttribute
public String test2(@ModelAttribute("test") String str){
System.out.println(str);
return "/test/hello";
}
以上是在后台Controller层获取值的两种方法,若是在前台页面的话,直接利用EL表达式就能够取到数据。