Sunday, April 8, 2018

Spring MVC - RedirectAttributes with FlashAttribute Example

You can use RedirectAttributes object which was introduced in Spring MVC 3.1 and populate it with data you want to keep for redirection. This is a very common usecase in web app development.
PRG - Post/Redirect/Get Pattern
Post/Redirect/Get (PRG) is a web development design pattern that prevents some duplicate form submissions, creating a more intuitive interface for user agents (users). PRG supports bookmarks and the refresh button in a predictable way that does not create duplicate form submissions.
A Controller with PRG Pattern
 @RequestMapping(value = "/accounts", method = RequestMethod.POST)
 public String handle(Account account, BindingResult result, RedirectAttributes redirectAttrs) {
   if (result.hasErrors()) {
     return "accounts/new";
   // Save account ...
   redirectAttrs.addAttribute("id", account.getId()).addFlashAttribute("message", "Account created!");
   return "redirect:/accounts/{id}";
addFlashAttribute actually stores the attributes in a flashmap(which is internally maintained in the users session and removed once the next redirected request gets fulfilled), on the other addAttribute essentially constructs request parameters out of your attributes and redirects to the desired page with the request parameters. So the advantage 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.

Spring Documentation

A FlashMap provides a way for one request to store attributes intended for use in another. This is most commonly needed when redirecting from one URL to another — e.g. the Post/Redirect/Get pattern. A FlashMap is saved before the redirect (typically in the session) and is made available after the redirect and removed immediately.
A FlashMap can be set up with a request path and request parameters to help identify the target request. Without this information, a FlashMap is made available to the next request, which may or may not be the intended recipient. On a redirect, the target URL is known and a FlashMap can be updated with that information. This is done automatically when the org.springframework.web.servlet.view.RedirectView is used.
You can buy my ebook for complete collection of questions and answer of Java Interview Questions

No comments:

Post a Comment

Your comment will be published after review from moderator