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
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.