spring mvc3中的addFlashAttribute方法
記得在spring mvc2中,當保存POJO到數據庫後,要返回成功頁面,若是這個時候要帶點信息,
則要這樣:
- //第三個參數(UserModel user)默認爲綁定對象
- @RequestMapping(value = "/user/save", method = RequestMethod.POST)
- public ModelAndView saveUser(HttpServletRequest request, HttpServletResponse response,UserModel user) throws Exception {
- ModelAndView mv = new ModelAndView("/user/save/result");//默認爲forward模式
- // ModelAndView mv = new ModelAndView("redirect:/user/save/result");//redirect模式
- mv.addObject("message","保存用戶成功!");
- return mv;
- }
而在spring mvc 3.1後,能夠這樣
- @RequestMapping(value = "/user/save", method = RequestMethod.POST)
- public ModelAndView saveUser(UserModel user, RedirectAttributes redirectAttributes) throws Exception {
- redirectAttributes.addFlashAttribute("message", "保存用戶成功!");//使用addFlashAttribute,參數不會出如今url地址欄中
- return "redirect:/user/save/result";
- }
來個稍微完整點的例子,首先是一個表單,在其中填入一些信息:
- <form:form id="myform" action="saveUserDetails.action" method="POST" commandName="user">
- <form:input type="text" name="firstName" path="firstName"/>
- <form:input type="text" name="lastName" path="lastName"/>
- <form:input type="text" name="email" path="email"/>
- <input type="submit" value="submit">
- </form:form>
-
則在controller中,能夠這樣:
- @RequestMapping(value="/saveUserDetails.action", method=RequestMethod.POST)
- public String greetingsAction(@Validated User user,RedirectAttributes redirectAttributes){
-
- someUserdetailsService.save(user);
-
- redirectAttributes.addFlashAttribute("firstName", user.getFirstName());
- redirectAttributes.addFlashAttribute("lastName", user.getLastName())
- return "redirect:success.html";
- }
success.html:
<div>
<h1>Hello ${firstName} ${lastName}. Your details stored in our database.</h1>
</div><br>
但若是F5的時候,會發現參數丟失,由於flash scope其實只支持redirect的,因此能夠判斷下:
- @RequestMapping(value="/success.html", method=RequestMethod.GET)
- public String successView(HttpServletRequest request){
- Map<String,?> map = RequestContextUtils.getInputFlashMap(request);
- if (map!=null)
- return "success";
- else return "redirect:someOtherView"; //給出其餘提示信息
歡迎關注本站公眾號,獲取更多信息