Servlet sendRedirect() Method

sendRedirect() is a such type of method which redirects the response to another resource. This method makes the client(browser) to create a new request to get to the resource. The client can see the new url in the browser. sendRedirect() accepts relative URL, so it can go for resources inside or outside the server.

The main difference between a redirect and a request dispatching is that, redirect method makes the client(browser) create a new request to get to the resource, the user can see the new URL while request dispatching get the resource in same request and URL does not changes. Also, another very important difference is that, sendRedirect() works on response object while request dispatch work on request object.

Let's see a demo program:

When to use sendRedirect() method?

  • • When a Programmer want to sent the client request to another Web site on a different server.
  • • To redirect the errors to another resource (like Servlet or JSP).
  • • To send any HTML form existing on the server to client.
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServletDemo extends HttpServlet {

   protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        PrintWriter pw = response.getWriter();
        try {
        }finally {         

About the Author

Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc