70

This will redirect a request with a temporary 302 HTTP status code:

HttpServletResponse response;
response.sendRedirect("http://somewhere");

But is it possible to redirect it with a permanent 301 HTTP status code?

z12345
  • 2,186
  • 4
  • 20
  • 28

2 Answers2

119

You need to set the response status and the Location header manually.

response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", "http://somewhere/");

Setting the status before sendRedirect() won't work as sendRedirect() would overridde it to SC_FOUND afterwards.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • `Sends a temporary redirect response to the client using the specified redirect location URL.` Ok - you're right. I actually thought it would behave similar to the way it works with sendError after setting a status. Hence the 'try setting' in my post xD – chzbrgla Jan 27 '12 at 14:04
  • 3
    The `sendError()` takes the status as argument, `sendRedirect()` not. It implicitly sets 302, regardless of the current status. – BalusC Jan 27 '12 at 14:05
  • 9
    Thank you, this works. To commit the response, you also have to flush the buffer: `response.flushBuffer();` – z12345 Jan 27 '12 at 15:46
  • @k12345: the container ought to do this implicitly. Actually, you do not need to write anything to the response body. – BalusC Jan 27 '12 at 15:51
  • @z12345 is right. Without response.flushBuffer(); it does not work – egemen Oct 05 '18 at 08:55
  • 1
    @egemen: It may not be necessary. Either you're incorrectly continuing the code flow after having set the response status (e.g. forwarding to some JSP instead of returning from the method), or you've hit a bug in your server. In that case report issue to vendor of servletcontainer. – BalusC Oct 05 '18 at 12:47
-1

I used the following code, but didn't worked for me.

String newURL = res.encodeRedirectURL("...");
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.sendRedirect(newURL);

then I tried this piece of code it worked for me

String newURL = res.encodeRedirectURL("...");
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", newURL);

this worked for me, I had the same issue

how to set status to 301 while redirecting

ParagFlume
  • 959
  • 8
  • 17