小编典典

在Spring MVC 3.1中重定向后如何读取Flash属性?

spring-mvc

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

}

我缺少什么?


阅读 363

收藏
2020-06-01

共1个答案

小编典典

使用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
  }
}

PS你可以做回return new ModelAndView("redirect:/foo/bar");handlePost

编辑

JavaDoc说:

调用该方法时,RedirectAttributes模型为空,除非该方法返回重定向视图名称或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在我的代码中使用RedirectViewmodel.asMap()方法,效果很好。

2020-06-01