记得在spring mvc2中,当保存POJO到数据库后,要返回成功页面,如果这个时候要带点信息,
则要这样:
Java代码:
- //第三个参数(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后,可以这样
Java代码:
- @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";
- }
来个稍微完整点的例子,首先是一个表单,在其中填入一些信息:
Java代码:
- <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中,可以这样:
Java代码:
- @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的,所以可以判断下:
Java代码:
- @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"; //給出其他提示信息
原文地址:http://www.software8.co/wzjs/java/2943.html