I usually post about Spring stuff on Twitter - you can follow me there:
Follow @baeldung1. Overview
This article will focus on implementing a Redirect in Spring and will discuss the reasoning behind each strategy.
2. Why Do A Redirect?
Let’s first consider the reasons why you may need to do a redirect in a Spring application.
There are a host of examples and reasons of course. One simple one might be POSTing form data, working around the double submission problem, or simply delegating the execution flow to another controller method.
A quick side note here is that the typical Post/Redirect/Get pattern doesn’t fully address double submission issues – problems such as refreshing the page before the initial submission has completed may still result in a double submission.
3. Redirect with RedirectView
Let’s start with this simple approach – and go straight to an example:
@Controller @RequestMapping("/") public class RedirectController { @RequestMapping(value = "/redirectWithRedirectView", method = RequestMethod.GET) public RedirectView redirectWithUsingRedirectView(RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("flashAttribute", "redirectWithRedirectView"); redirectAttributes.addAttribute("attribute", "redirectWithRedirectView"); return new RedirectView("redirectedUrl"); } }
Behind the scenes, RedirectView will trigger a HttpServletResponse.sendRedirect() – which will perform the actual redirect.
Notice here how we’re injecting the redirect attributes into the method – the framework will do the heavy lifting here and allow us to interact with these attributes cleanly.
We’re adding the model attribute attribute – which will be exposed as HTTP query parameter. The model must contain only objects – generally Strings or objects that can be converted to Strings.
Let’s now test our redirect – with the help of a simple curl command:
curl -i http://localhost:8080/spring-rest/redirectWithRedirectView
The result will be:
HTTP/1.1 302 Found Server: Apache-Coyote/1.1 Location: http://localhost:8080/spring-rest/redirectedUrl?attribute=redirectWithRedirectView
4. Redirect with the prefix redirect:
The previous approach – using RedirectView – is suboptimal for a few reasons.
First- we’re now coupled to the Spring API, because we’re using the RedirectView directly in our own code.
Second – we now need to know from the start, when implementing that controller operation – that the end result will always be a redirect – which may not always be the case.
A better option is using the prefix redirect: – the redirect view name is injected into the controller like any other logical view name. The controller is not even aware that redirection is happening.
Here’s what that looks like:
@Controller @RequestMapping("/") public class RedirectController { @RequestMapping(value = "/redirectWithRedirectPrefix", method = RequestMethod.GET) public ModelAndView redirectWithUsingRedirectPrefix(ModelMap model) { model.addAttribute("attribute", "redirectWithRedirectPrefix"); return new ModelAndView("redirect:/redirectedUrl", model); } }
When a view name is returned with the prefix redirect: – the UrlBasedViewResolver (and all its subclasses) will recognize this as a special indication that a redirect needs to happen. The rest of the view name will be used as the redirect URL.
A quick but important note here is that – when we use this logical view name here – redirect:/redirectedUrl – we’re doing a redirect relative to the current Servlet context.
We can use a name such as redirect: http://localhost:8080/spring-redirect/redirectedUrl if we need to redirect to an absolute URL.
So now, when we execute the curl commend:
curl -i http://localhost:8080/spring-rest/redirectWithRedirectPrefix
We’ll immediately get redirected:
HTTP/1.1 302 Found Server: Apache-Coyote/1.1 Location: http://localhost:8080/spring-rest/redirectedUrl?attribute=redirectWithRedirectPrefix
5. Forward with the prefix forward:
Let’s now see how to do something slightly different – a forward.
Before the code, let’s go over a quick high level overview of the semantics of forward vs redirect:
- redirect will respond with a 302 and the new URL in the Location header; the browser/client will then make another request to the new URL
- forward happens entirely on a server side; the Servlet container forwards the same request to the target URL; the URL won’t change in the browser
Now let’s look at the code:
@Controller @RequestMapping("/") public class RedirectController { @RequestMapping(value = "/forwardWithForwardPrefix", method = RequestMethod.GET) public ModelAndView redirectWithUsingForwardPrefix(ModelMap model) { model.addAttribute("attribute", "forwardWithForwardPrefix"); return new ModelAndView("forward:/redirectedUrl", model); } }
Same as redirect:, the forward: prefix will be resolved by UrlBasedViewResolver and its subclasses. Internally, this will create an InternalResourceView which does a RequestDispatcher.forward() to the new view.
When we execute the command with curl:
curl -I http://localhost:8080/spring-rest/forwardWithForwardPrefix
The result will be:
HTTP/1.1 405 Method Not Allowed Server: Apache-Coyote/1.1 Allow: GET Content-Type: text/html;charset=utf-8
To wrap up, compared to the 2 requests that we had in the case of the redirect solution, in this case we only have a single request going out from the browser/client to the server side. The attribute that was previously added by the redirect is of course missing as well.
6. Attributes With RedirectAttributes
Next – let’s look closer at passing attributes in a redirect – making full use the framework with RedirectAttribures:
@RequestMapping(value = "/redirectWithRedirectAttributes", method = RequestMethod.GET) public RedirectView redirectWithRedirectAttributes(RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("flashAttribute", "redirectWithRedirectAttributes"); redirectAttributes.addAttribute("attribute", "redirectWithRedirectAttributes"); return new RedirectView("redirectedUrl"); }
As we saw before, we can inject the attributes object in the method directly – which makes this mechanism very easy to use.
Notice also that we are adding a flash attribute as well – this is an attribute that won’t make it into the URL. What we can achieve with this kind of attribute is – we can later access the flash attribute using @ModelAttribute(“flashAttribute”) only in method that is the final target of the redirect:
@RequestMapping(value = "/redirectedUrl", method = RequestMethod.GET) public ModelAndView redirection( ModelMap model, @ModelAttribute("flashAttribute") Object flashAttribute) { model.addAttribute("redirectionAttribute", flashAttribute); return new ModelAndView("redirection", model); }
So, to wrap up – if we test the functionality with curl:
curl -i http://localhost:8080/spring-rest/redirectWithRedirectAttributes
The result will be:
HTTP/1.1 302 Found Server: Apache-Coyote/1.1 Set-Cookie: JSESSIONID=4B70D8FADA2FD6C22E73312C2B57E381; Path=/spring-rest/; HttpOnly Location: http://localhost:8080/spring-rest/redirectedUrl; jsessionid=4B70D8FADA2FD6C22E73312C2B57E381?attribute=redirectWithRedirectAttributes
That way, using RedirectAttribures instead of a ModelMap gives us ability to only share some attributes between the two methods that are involved in the redirect operation.
7. An Alternative Configuration Without The Prefix
Let’s now explore an alternative configuration – a redirect without using the prefix.
To achieve this, we need to use a org.springframework.web.servlet.view.XmlViewResolver:
<bean class="org.springframework.web.servlet.view.XmlViewResolver"> <property name="location"> <value>/WEB-INF/spring-views.xml</value> </property> <property name="order" value="0" /> </bean>
Instead of org.springframework.web.servlet.view.InternalResourceViewResolver we used in the previous configuration:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>
We also need to define a RedirectView bean in the configuration:
<bean id="RedirectedUrl" class="org.springframework.web.servlet.view.RedirectView"> <property name="url" value="redirectedUrl" /> </bean>
Now we can trigger the redirect by reference this new bean by id:
@Controller @RequestMapping("/") public class RedirectController { @RequestMapping(value = "/redirectWithXMLConfig", method = RequestMethod.GET) public ModelAndView redirectWithUsingXMLConfig(ModelMap model) { model.addAttribute("attribute", "redirectWithXMLConfig"); return new ModelAndView("RedirectedUrl", model); } }
8. Conclusion
This article illustrated 3 different approaches to implementing a redirect in Spring as well as how to handle/pass attributes when doing these redirects.