How to send redirect from Java Servlet
- Details
- Written by Nam Ha Minh
- Last Updated on 28 June 2019   |   Print Email
In Java web development, to redirect the users to another page, you can call the following method on the HttpServletResponse object response:
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 committed
So you should pay attention to this behavior when using sendRedirect(). Call to sendRedirect() should be the last statement in the workflow.
Related Java Servlet Tutorials:
- How to Forward Request from Java Servlet to JSP with Data
- jsp:forward standard action examples
- Java Servlet for beginners (XML)
- Java Servlet for beginners (Annotation)
- Java Servlet and JSP Hello World Tutorial with Eclipse, Maven and Apache Tomcat
- How to use Cookies in Java web application
- How to use Session in Java web application
Comments
Thank you