response.sendRedirect(String location)
Technically, the server sends a HTTP status code 302 (Moved Temporarily) to the client. Then the client performs URL redirection to the specified location. The location in the sendRedirect() method can be a relative path or a completely different URL in absolute path.For example, in a Java servlet’s doGet()/doPost() method:response.sendRedirect("login.jsp");This statement redirects the client to the login.jsp page relative to the application’s context path.But this redirects to a page relative to the server’s context root:
response.sendRedirect("/login.jsp");And the following statement redirects the client to a different website:
response.sendRedirect("https://www.yoursite.com");Note that this method throws IllegalStateException if it is invoked after the response has already been committed. For example:
PrintWriter writer = response.getWriter(); writer.println("One more thing..."); writer.close(); String location = "https://www.codejava.net"; response.sendRedirect(location);Here, the writer.close() statement commits the response so the call to sendRedirect() below causes an IllegalStateException is thrown:
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committedSo you should pay attention to this behavior when using sendRedirect(). Call to sendRedirect() should be the last statement in the workflow.