頁面仍然使用 JSP,在跳轉時若是想傳遞參數則須要用到類 RedirectAttributes。javascript
首先看看如何打開一個普通頁面:java
// 登陸頁面(每一個頁面都要獨立的 Action 來支持其呈現) @RequestMapping(value = "/Index", method = RequestMethod.GET) public String Index(Model model) { model.addAttribute("name", "Tom"); return "UserLogin/Index"; }
很簡單,直接爲 Model 對象添加屬性對便可,而後在 JSP 頁面裏,經過 ${name} 就能夠獲得它的值 Tom。app
那麼,在頁面發生了跳轉的狀況下該如何傳遞屬性對參數呢?這時 RedirectAttributes 就要隆重上場了。
先上一段代碼:jsp
// 登陸動做 @RequestMapping(value = "/Login", method = RequestMethod.POST) public String Login(UserLoginDTO userLoginDTO, RedirectAttributes attr) { System.out.println("--Login"); System.out.println("accountId = " + userLoginDTO.getAccountId()); System.out.println("pwd = " + userLoginDTO.getPwd()); if (userLoginDTO.getAccountId() == "") { attr.addFlashAttribute("msg", "賬號不能爲空"); return "redirect:/UserLogin/Index"; } if (userLoginDTO.getPwd() == "") { attr.addFlashAttribute("msg", "密碼不能爲空"); return "redirect:/UserLogin/Index"; } attr.addFlashAttribute("msg", "登陸一切正常"); System.out.println(attr); return "redirect:/UserLogin/LoginSuccess"; }
Login 方法的第二個參數已再也不是 Model 了,而是 RedirectAttributes,在方法體中,隨着代碼的各類判斷,須要去往的頁面也不相同,隨之須要傳遞的消息也能夠自由變化,好比:code
attr.addFlashAttribute("msg", "賬號不能爲空"); return "redirect:/UserLogin/Index";
在用法上與 Model 很類似,都是屬性對,上述代碼將跳轉至 Index.jsp 頁面。
衆所周知,在 Spring MVC 裏頁面呈現以前都須要經由對應的方法來引導,接下來爲了驗證這裏的屬性對是否真的已傳遞出去,能夠經過如下代碼來驗證:對象
// 登陸頁面(每一個頁面都要獨立的 Action 來支持其呈現) @RequestMapping(value = "/Index", method = RequestMethod.GET) public String Index(Model model) { System.out.println("--Index"); System.out.println(model); return "UserLogin/Index"; }
打印出來的結果是:blog
--Index {msg=賬號不能爲空}
能夠看到,attr.addFlashAttribute() 已將參數傳遞出去。在 JSP 頁面裏用法不變,即 ${msg} 就能夠獲得它的值。ip