I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

This article will focus on implementing a Redirect in Spring and will discuss the reasoning behind each strategy.

Further reading:

Redirect to Different Pages after Login with Spring Security

Example of how to Redirect to different pages after Login with Spring Security.

Read more

Spring Security – Redirect to the Previous URL After Login

A short example of redirection after login in Spring Security

Read more

Control the Session with Spring Security

Configure Sessions with Spring Security - set up Concurrent Sessions, enable Session Fixation Protection and prevent URLs from containing Session information.

Read more

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 many possible examples and reasons of course. One simple one might be POSTing form data, working around the double submission problem, or just delegating the execution flow to another controller method.

A quick side note here is that the typical Post/Redirect/Get pattern doesn’t adequately 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 the RedirectView

Let’s start with this simple approach – and go straight to an example:

@Controller
@RequestMapping("/")
public class RedirectController {
    
    @GetMapping("/redirectWithRedirectView")
    public RedirectView redirectWithUsingRedirectView(
      RedirectAttributes attributes) {
        attributes.addFlashAttribute("flashAttribute", "redirectWithRedirectView");
        attributes.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.

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 code.

Second – we now need to know from the start, when implementing that controller operation – that the 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 {
    
    @GetMapping("/redirectWithRedirectPrefix")
    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 a redirect: http://localhost:8080/spring-redirect-and-forward/redirectedUrl if we need to redirect to an absolute URL.

So now, when we execute the curl command:

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 {
    
    @GetMapping("/forwardWithForwardPrefix")
    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

We will get HTTP 405 (Method not allowed):

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 two 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 the RedirectAttributes

Next – let’s look closer at passing attributes in a redirect – making full use the framework with RedirectAttribures:

@GetMapping("/redirectWithRedirectAttributes")
public RedirectView redirectWithRedirectAttributes(RedirectAttributes attributes) {
 
    attributes.addFlashAttribute("flashAttribute", "redirectWithRedirectAttributes");
    attributes.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 the method that is the final target of the redirect:

@GetMapping("/redirectedUrl")
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

We will be redirected to the new location:

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 the ability only to 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 an 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 referencing this new bean by id:

@Controller
@RequestMapping("/")
public class RedirectController {
    
    @GetMapping("/redirectWithXMLConfig")
    public ModelAndView redirectWithUsingXMLConfig(ModelMap model) {
        model.addAttribute("attribute", "redirectWithXMLConfig");
        return new ModelAndView("RedirectedUrl", model);
    }
}

And to test it, we’ll again use the 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

8. Redirecting an HTTP POST Request

For use cases like bank payments, we might need to redirect an HTTP POST request. Depending upon the HTTP status code returned, POST request can be redirected to an HTTP GET or POST.

As per HTTP 1.1 protocol reference, status codes 301 (Moved Permanently) and 302 (Found) allow the request method to be changed from POST to GET. The specification also defines the corresponding 307 (Temporary Redirect) and 308 (Permanent Redirect) status codes that don’t allow the request method to be changed from POST to GET.

Now let’s look at the code for redirecting a post request to another post request:

@PostMapping("/redirectPostToPost")
public ModelAndView redirectPostToPost(HttpServletRequest request) {
    request.setAttribute(
      View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT);
    return new ModelAndView("redirect:/redirectedPostToPost");
}
@PostMapping("/redirectedPostToPost")
public ModelAndView redirectedPostToPost() {
    return new ModelAndView("redirection");
}

Now, let’s test the redirect of POST using the curl command:

curl -L --verbose -X POST http://localhost:8080/spring-rest/redirectPostToPost

We are getting redirected to the destined location:

> POST /redirectedPostToPost HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.49.0
> Accept: */*
> 
< HTTP/1.1 200 
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Tue, 08 Aug 2017 07:33:00 GMT

{"id":1,"content":"redirect completed"}

9. Conclusion

This article illustrated three different approaches to implementing a redirect in Spring, how to handle/pass attributes when doing these redirects as well as how to handle redirects of HTTP POST requests.

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

newest oldest most voted
Notify of
jmzc
Guest
jmzc

Thanks.

But I’ve got a question.

I don’t understand where flashAttribute is stored in.

I guess it’s stored in session but it’s not clear for me .

alexey semenyuk
Guest
alexey semenyuk

From Spring docs: http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-flash-attributes: Flash
attributes are saved temporarily before the redirect (typically in the
session) to be made available to the request after the redirect and
removed immediately.

Marcel Stör
Guest

What’s the most convenient way to change from HTTP 302 (what Spring uses) to 301, 303 or 307? Haven’t figured out yet how to do that with “redirect:/” or RedirectView.

Eugen Paraschiv
Guest

The semantics of the 301 vs 308 are clear in the spec, but I haven’t explore how much flexibility there is in Spring MVC to handle the 308. I’ve added it to the content calendar, so I’ll look into it (and update the article here). Cheers,
Eugen.

alexey semenyuk
Guest
alexey semenyuk

You can use for this purposes setStatusCode, for example:
RedirectView redirectView = new RedirectView(“redirectedUrl”);
redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY);

Gamy
Guest
Gamy

Nice article, but do you know how to redirect a “post” request to another “post”? All I have succeeded to do so far is to have my post request transformed to a get which sadly result into a 405 . Like Marcel says what’s the way to use 307 or 308?

Eugen Paraschiv
Guest

Hey Gamy – that’s an interesting question – I’m adding it to the content calendar and I’ll update the article to answer the question. Cheers,
Eugen.

Steve Donovan
Guest
Steve Donovan

Hey Eugene i’ve something like : ————- @ResponseStatus(HttpStatus.TEMPORARY_REDIRECT) @RequestMapping(value = “/index”, method = RequestMethod.GET, params = {“paramA”, “paramB”}) public String doSomething(@RequestParam(“paramA”) final String paramA, @RequestParam(“paramB”) final String paramB) { … do some stuff … return String.format(“redirect:/index.html?paramC=%s”, “blah blah; } ————- As you can see the RequestMapping is same as static file I wish to redirect to.It fails because its trying to redirect back to same endpoint. I need to tell it to look elsewhere when params don’t match rather than it just failing?

Eugen Paraschiv
Guest

Hey Steve – that’s an interesting scenario here. Yes, simply put you’ll need to redirect to some other URL – you can’t simply redirect back to the same one, as that would of course create a loop.
Hope that helps. Cheers,
Eugen.

Steve Donovan
Guest
Steve Donovan

Thanks for prompt reply Eugene. I was hoping that given it can differentiate between request mappings based on params ie you can have multplie mappings to same name but different params, that it would be able to do same with mapping and static resource.

Eugen Paraschiv
Guest

Hey Steve, sure thing, happy to help.
Theoretically it should. However, there are some weird corner cases where it doesn’t map requests as you might expect – that’s why it’s very useful to dig into the framework code and see what’s going on.
Hope you sort things out like that. Cheers,
Eugen.

Oleg
Guest
Oleg

One more great article Eugene, thank you! Wondering what kind of “redirect” can be used to pass parameters from a controller to a view with the following criterias: – parameters don’t appear in a URL – parameters are not removed after page refresh (as flashAttributes do) I thought redirectView.setExposeModelAttributes(false) will do the job, but this method actually turns parameters off and they are not accessible in a view at all. I don’t want to use flash attributes coz they disappear on refresh. To use a session? But in this case you have to remember what was put to session and… Read more »

Eugen Paraschiv
Guest

Hey Oleg, sorry for the late response (vacation). No, I don’t think there’s a good way to do that just via a redirect, without any extra logic you need to maintain yourself. Yeah, you’d very likely have to store them in the session (as flash attributes are) and then refer to them manually.
Haven’t looked into it a lot, so I might be wrong, do let me know if you found a way. Cheers,
Eugen.