sendRedirect() Method in Servlet

sendRedirect() method redirects the response to another resource. This method actually 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.


Servlet: sendRedirect() and Request Dispatcher

The main difference between a redirection and a request dispatching is that, redirection makes the client(browser) create a new request to get to the resource, the user can see the new URL while request dispatch 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.


Example demonstrating usage of sendRedirect()


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

   protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try { 
            response.sendRedirect("https://www.studytonight.com");
        }
        finally {            
            out.close();
        }
    }
}

Difference between forward() and sendRedirect()



forward() sendRedirect()
It works at server side. It works at client side.
It always sends the same request and response object. It always sends new request for the object.
It only works within the server. It works both inside and outside the server.
In this method, all the processing is handled by web container internally. In this method, all the processing is handled by another servlet.
It is faster. It is slower.
Using forward() method address can be seen in address bar. Using forward() method address can not be seen in address bar.
RequestDispatcher interface is used for declaration. HttpServletResponse is used for declaration.
It is very useful in MVC design pattern to hide direct access. It is not useful in MVC design pattern to hide direct access.
It reuses the object. It does not reuse the object.
Example: request.getRequestDispacher("servlet_1").forward(request response); Example: response.sendRedirect("Servlet_1");