Spring MVC Redirect Views Example

In a Spring application you may need to redirect to a view for many reasons
1. On a form submission, a controller will get the POST data to process. If after processing the data we internally forward to request to another Controller, then the new Controller will also see the same POST data used by the old Controller. This may lead to problems if the new Controller was expecting to see other Data.
2. Another problem is the multiple submission of the same form if we do a internal forward after the form submission.

Spring MVC provides ways to redirect to views using various techniques. In this post lets see the various Spring MVC Redirect Views examples.

1. Using RedirectView

We can use a instance of the RedirectView to redirect to the view we want. RedirectView behaves diffently as supposed to to normal view resolution. The DispatcherServlet will not interfere in the RedirectView works :). RedirectView calls the HttpServletResponse.sendRedirect()
to send a HTTP redirect to the client.

2. Using redirect prefix

Another way to redirect to a view is using the redirect prefix.
redirect prefix is associated with a view name, where we need to redirect the page to. Using redirect prefix is a better way of handling redirects as it is not directly coupled to the the Controller.
As you can see, when using the RedirectView the Controller has to knows that a redirection will be happening. But this couples things too tightly. Controller should not care how the response is handled. Hence using redirect prefix is more useful.

UrlBasedViewResolver resolves the view name associated with the redirect prefix.

3. Using forward prefix

Similar to redirect prefix, we can use the forward prefix. UrlBasedViewResolver resolves the view name associated with the forward prefix.
RequestDispatcher.forward() is used for the forward prefix.

How to pass attributes to the Redirected views

RedirectAttributes can be used to pass attributes to the Redirected Views. If the method redirects, the RedirectAttributes are used. Otherwise the the model is used. To use the RedirectAttributes we need to declare it as the methods parameter.

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn