Introduction to sendRedirect() Method

The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file.

It works at client side because it uses the url bar of the browser to make another request. So, it can work inside and outside the server.

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.

Difference between forward() and sendRedirect() method

There are many differences between the forward() method of RequestDispatcher and sendRedirect() method.

forward() method sendRedirect() method
The forward() method works at server side. The sendRedirect() method works at client side.
It sends the same request and response objects to another servlet. It always sends a new request.
It can work within the server only. It can be used within and outside the server.
Example: request.getRequestDispacher("servlet2").forward(request,response); Example: response.sendRedirect("servlet2");
Syntax: public void sendRedirect(String URL)throws IOException; Example : response.sendRedirect("http://www.javatportal.com");

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("http://www.javatportal.com");

        }finally {            

            out.close();

        }

    }

}