Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpServletResponse sendRedirect permanent

Tags:

java

servlets

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?

like image 559
z12345 Avatar asked Jan 27 '12 13:01

z12345


People also ask

What is sendRedirect method and its use?

sendRedirect() method redirects the response to another resource, inside or outside the server. It makes the client/browser to create a new request to get to the resource. It sends a temporary redirect response to the client using the specified redirect location URL.

What's the difference between sendRedirect and forward methods?

The main important difference between the forward() and sendRedirect() method is that in case of forward(), redirect happens at server end and not visible to client, but in case of sendRedirect(), redirection happens at client end and it's visible to client.

How do you pass variables in response sendRedirect?

If you forward the request, you can use setAttribute to put your variable in the request scope, which can easily be retrieved in your JSP. request. setAttribute( "temp" , yourVar); RequestDispatcher dispatcher = request.


1 Answers

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.

like image 182
BalusC Avatar answered Oct 31 '22 18:10

BalusC