在開發中,有時會遇到 controller 之間跳轉的狀況,並且有時在跳轉的時候須要把不一樣的參數傳遞過去,好比從controller a
跳轉到controller b
,再從controller b
到前端頁面,而且把controller a
裏的數據好比String
、List
、Map
或者對象傳遞到頁面,等等相似狀況。結合查找網上的資料以及本身的試驗,現總結以下。html
注: 本文實例均在springmvc
框架下,其餘架構自行調整。前端
使用返回 String 的方式: return "forward:Xxx.action";
java
@RequestMapping("/index") public String logout(ModelMap model, RedirectAttributes attr) { return "forward:test.action"; }
若是使用ModelAndView
方式: return new ModelAndView("forward:/tolist");
ajax
注:此後,都以返回String的方式來敘述。spring
@RequestMapping("/index") public String logout(ModelMap model, RedirectAttributes attr) { return "redirect:test.action"; }
**forward
**是請求轉發,是服務器端行爲,至關於一次請求,地址欄的 URL 不會改變。 **redirect
**是請求重定向,是客戶端行爲,至關於兩次請求,地址欄的 URL 會改變。安全
return "redirect:/login.action?name="+ name;
login.action
:服務器
@RequestMapping("/login") public String login(HttpServletRequest request, ModelMap model, RedirectAttributes attr ) { String name = request.getParameter("name"); model.addAttribute("name",name); return "login"; }
而後在login.html
接收,用${name}
便可。session
拼接url傳參的缺點:架構
RedirectAttributes
是 Spring mvc 3.1 版本以後出來的一個功能,專門用於重定向以後還能帶參數跳轉的的工具類。 它有兩種帶參的方式:mvc
第一種:redirectAttributes.addAttributie("prama",value);
redirectAttributes.addAttribute("prama1",value1); redirectAttributes.addAttribute("prama2",value2); return:"redirect:/path/list"
這種方法至關於在重定向連接地址追加傳遞的參數:return:"redirect:/path/list?prama1=value1&prama2=value2
(直接追加參數會將傳遞的參數暴露在連接的地址上,很是的不安全,慎用)
第二種:redirectAttributes.addFlashAttribute("prama",value);
redirectAttributes.addFlashAttribute("prama1",str); redirectAttributes.addFlashAttribute("prama2",list); redirectAttributes.addFlashAttribute("prama3",map); return:"redirect:/path/list.jsp" ;
此方法隱藏了參數,連接地址上不直接暴露,可是能且只能在重定向的頁面上獲取prama的值。其原理是參數放到了session
中,session
在跳轉以後立刻移除對象。若是重定向到一個controller
,是取不到該prama的值的。
總的來講,controller
之間跳轉而後把參數傳到前臺頁面,這種方式實現起來費力不討好,對於數據傳遞以及前臺頁面的接收展現來講不是很友好,其實能夠換成用ajax
方式來作,調用後臺數據更加靈活而且局部刷新功能也更加友好。But,多一種方式,多一種選擇。