Spring MVC: flash attribute vs model attribute

后端 未结 1 963
[愿得一人]
[愿得一人] 2020-12-29 13:07

What is the different between flash and model attribute?

I want to store an object and display it in my JSP as well as reuse it in other controller

相关标签:
1条回答
  • 2020-12-29 13:42

    If we want to pass the attributes via redirect between two controllers, we cannot use request attributes (they will not survive the redirect), and we cannot use Spring's @SessionAttributes (because of the way Spring handles it), only an ordinary HttpSession can be used, which is not very convenient.

    Flash attributes provide a way for one request to store attributes intended for use in another. This is most commonly needed when redirecting — for example, the Post/Redirect/Get pattern. Flash attributes are saved temporarily before the redirect (typically in the session) to be made available to the request after the redirect and removed immediately.

    Spring MVC has two main abstractions in support of flash attributes. FlashMap is used to hold flash attributes while FlashMapManager is used to store, retrieve, and manage FlashMap instances.

    Example

    @Controller
    @RequestMapping("/foo")
    public class FooController {
    
      @RequestMapping(value = "/bar", method = RequestMethod.GET)
      public ModelAndView handleGet(Model model) {
        String some = (String) model.asMap().get("some");
        // do the job
      }
    
      @RequestMapping(value = "/bar", method = RequestMethod.POST)
        public ModelAndView handlePost(RedirectAttributes redirectAttrs) {
        redirectAttrs.addFlashAttribute("some", "thing");
    
        return new ModelAndView().setViewName("redirect:/foo/bar");
      }
    
    }
    

    In above example, request comes to handlePost, flashAttributes are added, and retrieved in handleGet method.

    More info here and here.

    0 讨论(0)
提交回复
热议问题