Unknown

Introduction to sendRedirect() Method

Introduction to sendRedirect() Method

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.

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("http:/ /www.studytonight.com");
        }finally {            
            out.close();
        }
    }
}