Issue
My understanding so far is on our controller request mapping method we can specify RedirectAttributes parameter and populate it with attributes for when the request gets redirected.
Example:
@RequestMapping(value="/hello", method=GET)
public String hello(RedirectAttributes redirAttr)
{
// should I use redirAttr.addAttribute() or redirAttr.addFlashAttribute() here ?
// ...
return "redirect:/somewhere";
}
The redirect attributes will then be available on the target page where it redirects to.
However RedirectAttributes class has two methods:
Have been reading Spring documentation for a while but I'm a bit lost. What is the fundamental difference between those two, and how should I choose which one to use?
Solution
Here is the difference:
addFlashAttribute()
actually stores the attributes in a flashmap (which is internally maintained in the userssession
and removed once the next redirected request gets fulfilled)addAttribute()
essentially constructs request parameters out of your attributes and redirects to the desired page with the request parameters.
So the advantage of addFlashAttribute()
will be that you can store pretty much any object in your flash attribute (as it is not serialized into request params at all, but maintained as an object), whereas with addAttribute()
since the object that you add gets transformed to a normal request param, you are pretty limited to the object types like String
or primitives.
Answered By - Biju Kunjummen