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

2022-09-01 01:55:35

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("/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");
  }

}

What I am missing?


答案 1

Use , it should have flash attributes prepopulated:Model

@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<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request);
  if (inputFlashMap != null) {
    String some = (String) inputFlashMap.get("some");
    // do the job
  }
}

P.S. You can do return in .return new ModelAndView("redirect:/foo/bar");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 , so maybe change handlePost to return string or :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);
}

I use in my code with and method and it works OK.RedirectAttributesRedirectViewmodel.asMap()


答案 2

Try this:

@Controller
public class FooController
{
    @RequestMapping(value = "/foo")
    public String handleFoo(RedirectAttributes redirectAttrs)
    {
        redirectAttrs.addFlashAttribute("some", "thing");
        return "redirect:/bar";
    }

    @RequestMapping(value = "/bar")
    public void handleBar(@ModelAttribute("some") String some)
    {
        System.out.println("some=" + some);
    }
}

works in Spring MVC 3.2.2


推荐