Redirecting a request using servlets and the "setHeader" method not working
As you can see, the response is still HTTP/1.1 200 OK
. To indicate a redirect, you need to send back a 302 status code:
response.setStatus(HttpServletResponse.SC_FOUND); // SC_FOUND = 302
Oh no no! That's not how you redirect. It's far more simpler:
public class ModHelloWorld extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
response.sendRedirect("http://www.google.com");
}
}
Also, it's a bad practice to write HTML code within a servlet. You should consider putting all that markup into a JSP and invoking the JSP using:
response.sendRedirect("/path/to/mynewpage.jsp");
Alternatively, you could try the following,
resp.setStatus(301);
resp.setHeader("Location", "index.jsp");
resp.setHeader("Connection", "close");