Spring RedirectView and RedirectAttributes Examples
- Details
- Written by Nam Ha Minh
- Last Updated on 29 April 2020   |   Print Email
A common case in Java web application development with Spring MVC is redirecting the users to a specific URL after an operation has completed. For example, when the user clicks Save button on a form to create a new item, he will be redirected to the items list page.
With Spring MVC, the code for such redirection would look like this:
@PostMapping("/items/save") public String saveItem(@ModelAttribute("item") Item item) { service.save(item); return "redirect:/items"; }
But, what if we want to send something to the redirected page? e.g. send a String “The item has been saved successful” to the items list page. In this case, you can use RedirectView and RedirectAttributes as follows:
@PostMapping("/items/save") public RedirectView saveItem(@ModelAttribute("item") Item item, RedirectAttributes ra) { service.save(item); RedirectView rv = new RedirectView("/items", true); ra.addFlashAttribute("message", "The item has been saved successfully."); return rv; }
Then the target page can use value of the message attribute directly.
Note that the URL specified in the RedirectView constructor can be absolute, context relative or current request relative. If you specify the redirect URL like this:
RedirectView rv = new RedirectView("/items");
Then it is relative to the web server root. If you want to use the redirect URL as relative to the application context path (context relative) then set the second flag to true:
RedirectView rv = new RedirectView("/items", true);
The addFlashAttribute() method of the RedirectAttributes class makes the value of the attribute available to the target page and also removes it immediately.
You can also use a String in form of “redirect:/URL” instead of a RedirectView object. For example:
@PostMapping("/items/save") public String saveItem(@ModelAttribute("item") Item item, RedirectAttributes ra) { service.save(item); ra.addFlashAttribute("message", "The item has been saved successfully."); return "redirect:/item"; }
That’s some code examples to do redirection with an attribute sent to the target page in Spring MVC.
References:
Other Spring Tutorials:
- Understand the core of Spring framework
- Understand Spring MVC
- Understand Spring AOP
- Spring MVC beginner tutorial with Spring Tool Suite IDE
- Spring MVC Form Handling Tutorial
- Spring MVC Form Validation Tutorial
- 14 Tips for Writing Spring MVC Controller
- Spring Web MVC Security Basic Example (XML Configuration)
- Understand Spring Data JPA with Simple Example
Comments