How to read flash attributes after redirection in Spring MVC 3.1?

后端 未结 3 2012
轮回少年
轮回少年 2020-11-28 22:58

I would like to know how to read a flash attributes after redirection in Spring MVC 3.1.

I have the following code:

@Controller
@RequestMapping(\"/fo         


        
3条回答
  •  野性不改
    2020-11-28 23:15

    Use Model, it should have flash attributes prepopulated:

    @RequestMapping(value = "/bar", method = RequestMethod.GET)
    public ModelAndView handleGet(Model model) {
      String some = (String) model.asMap().get("some");
      // do the job
    }
    

    or, alternatively, you can use RequestContextUtils#getInputFlashMap:

    @RequestMapping(value = "/bar", method = RequestMethod.GET)
    public ModelAndView handleGet(HttpServletRequest request) {
      Map inputFlashMap = RequestContextUtils.getInputFlashMap(request);
      if (inputFlashMap != null) {
        String some = (String) inputFlashMap.get("some");
        // do the job
      }
    }
    

    P.S. You can do return return new ModelAndView("redirect:/foo/bar"); in handlePost.

    EDIT:

    JavaDoc says:

    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.

    It doesn't mention ModelAndView, so maybe change handlePost to return "redirect:/foo/bar" string or RedirectView:

    @RequestMapping(value = "/bar", method = RequestMethod.POST)
    public RedirectView handlePost(RedirectAttributes redirectAttrs) {
      redirectAttrs.addFlashAttributes("some", "thing");
      return new RedirectView("/foo/bar", true);
    }
    

    I use RedirectAttributes in my code with RedirectView and model.asMap() method and it works OK.

提交回复
热议问题