我想知道如何在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属性:
@RequestMapping(value = "/bar", method = RequestMethod.GET)
public ModelAndView handleGet(Model model) {
String some = (String) model.asMap().get("some");
// do the job
}
或者,您也可以使用
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
}
}
附言您可以在
return new ModelAndView("redirect:/foo/bar");
中返回handlePost
。编辑:
JavaDoc说:
它没有提到
ModelAndView
,所以也许更改handlePost以返回"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()
,它可以正常工作。