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:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment