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表達式就能夠取到數據。