java – 如何在Spring MVC 3.1重定向后读取flash属性?

我想知道如何在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");
  }

}

我缺少什么?

使用模型,它应该具有预填充的闪存属性:

@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
  }
}

P.S。你可以做返回return New ModelAndView(“redirect:/ foo / bar”);在handlePost。

编辑:

JavaDoc说:

A RedirectAttributes model is empty when the method is called and is
never used unless the method returns a redirect view name or a
RedirectView.

它没有提到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()方法,它的工作确定。

http://stackoverflow.com/questions/11763779/how-to-read-flash-attributes-after-redirection-in-spring-mvc-3-1

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:java – 如何在Spring MVC 3.1重定向后读取flash属性?