Spring中RedirectAttributes对象重定向传参

时间:2023-12-24 09:42:25

Spring3中的FlashAttribute

为 了防止用户刷新重复提交,save操作之后一般会redirect到另一个页面,同时带点操作成功的提示信息。因为是Redirect,Request里 的attribute不会传递过去,如果放在session中,则需要在显示后及时清理,不然下面每一页都带着这个信息也不对。Spring在3.1才提 供了这个能力。

记得在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"; //給出其他提示信息