我想知道如何在Spring MVC 3.1中重定向后读取flash属性。
我有以下代码:
@Controller @RequestMapping("/foo") public class FooController { @RequestMapping(value = "/bar", method = RequestMethod.GET) public ModelAndView handleGet(...) { // I want to see my flash attributes here! } @RequestMapping(value = "/bar", method = RequestMethod.POST) public ModelAndView handlePost(RedirectAttributes redirectAttrs) { redirectAttrs.addFlashAttributes("some", "thing"); return new ModelAndView().setViewName("redirect:/foo/bar"); } }
我缺少什么?
使用Model,它应该预先填充Flash属性:
Model
@RequestMapping(value = "/bar", method = RequestMethod.GET) public ModelAndView handleGet(Model model) { String some = (String) model.asMap().get("some"); // do the job }
或者,您也可以使用RequestContextUtils#getInputFlashMap:
RequestContextUtils#getInputFlashMap
@RequestMapping(value = "/bar", method = RequestMethod.GET) public ModelAndView handleGet(HttpServletRequest request) { Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request); if (inputFlashMap != null) { String some = (String) inputFlashMap.get("some"); // do the job } }
PS你可以做回return new ModelAndView("redirect:/foo/bar");在handlePost。
return new ModelAndView("redirect:/foo/bar");
handlePost
编辑 :
JavaDoc说:
调用该方法时,RedirectAttributes模型为空,除非该方法返回重定向视图名称或RedirectView,否则永远不要使用它。
它没有提到ModelAndView,所以也许将handlePost更改为返回"redirect:/foo/bar"字符串或RedirectView:
ModelAndView
"redirect:/foo/bar"
RedirectView
@RequestMapping(value = "/bar", method = RequestMethod.POST) public RedirectView handlePost(RedirectAttributes redirectAttrs) { redirectAttrs.addFlashAttributes("some", "thing"); return new RedirectView("/foo/bar", true); }
我RedirectAttributes在我的代码中使用RedirectView和model.asMap()方法,效果很好。
RedirectAttributes
model.asMap()