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:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment

   


Comments 

#3EJP2021-03-09 19:21
Actually writing anything commits the response. See stackoverflow.com/.../...
Quote
#2ObiWan2020-02-27 09:55
Your link for forward not works. There is two pages for redirect
Quote
#1Deepak choudhary2018-10-04 20:14
This article is really helpful to me
Thank you
Quote