HttpServletResponse sendRedirect permanent

JavaServlets

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionz12345View Question on Stackoverflow
Solution 1 - JavaBalusCView Answer on Stackoverflow
Solution 2 - JavaParagFlumeView Answer on Stackoverflow