request redirection in servlet

h‮t‬tps://www.theitroad.com

In Java servlets, request redirection is the process of redirecting the client's request to a different resource or URL, instead of providing the requested resource from the current servlet. Request redirection can be used to forward the request to another servlet or JSP, or to redirect the request to an external resource.

There are two ways to perform request redirection in servlets:

  1. Using the RequestDispatcher interface: The RequestDispatcher interface provides two methods, forward() and include(), which can be used to forward or include the request to another servlet or JSP. The forward() method is used to forward the request to another resource, while the include() method is used to include the response of another resource in the current response.

  2. Using the HttpServletResponse interface: The HttpServletResponse interface provides the sendRedirect() method, which can be used to redirect the request to an external resource or URL. This method sends a response to the client with a status code of 302 (redirect), along with the URL of the new resource.

Here is an example of how to use the sendRedirect() method to redirect the client's request to an external URL:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String url = "http://www.example.com";
    response.sendRedirect(url);
}

In this example, the client's request is redirected to the URL "http://www.example.com". When the client receives the response with the status code 302, it automatically sends a new request to the specified URL.