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. I have use sessionAttribute
and it works fine in the JSP, but the problem is when I try to retrieve that model
attribute in other controller.
I lose some data. I searched around and found that flash attribute
allows to past past value to different controller, doesn't it?
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.
In Spring MVC, the @ModelAttribute annotation binds a method parameter or method return value to a named model attribute and then exposes it to a web view. It refers to the property of the Model object.
The @ModelAttribute annotation is used as part of a Spring MVC web app and can be used in two scenarios. Firstly, it can be used to inject data objects in the model before a JSP loads. This makes it particularly useful by ensuring that a JSP has all the data it needs to display itself.
@ModelAttribute can be used to expose command objects to a web view, using specific attribute names, by annotating corresponding parameters of an @RequestMapping method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With