request.getRequestDispatcher and response.sendRedirect

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Hello, in the previous two articles, we learned about request.getRequestDispatcher and response.sendRedirect. methods so that a resource can ask another resource to serve the response.

This post simply mentions the key differences between them.

request.getRequestDispatcher and response.sendRedirect.

RequestDispatcher

RequestDispatcher#forward method
RequestDispatcher#forward method

 

  • When you hit the url http://localhost:8080/ServletsJSPExamples/DispatcherServlet , request is made for DispatcherServlet
  • DispatcherServlet forwards the request to Hello.jsp.  The client is totally unaware of it.
  • Hello.jsp serves the request and server response to client. Requested url remains unchanged. Browser thinks the response has come from DispatcherServlet .
  • In RequestDispatcher, only one request is made from browser.

sendRedirect:

redirection in servlet

    1. When you hit url  http://localhost:8080/ServletsJSPExamples/DispatcherServlet  , request is made to the DispatcherServlet . As of now we have not done anything to redirect a request in servlet to another resource
    2. When the DispatcherServlet is executing, then the code  response.sendRedirect("Hello.jsp");   starts the process to redirect a request in servlet.
      • Http response sent by DispatcherServlet has status code 301 and a header called location with the new url i.e. url of JSP as value.
      • The browser receives this response and recognizes 301 status code which is used to redirect a request.
      • The browser finds the header called location and retrieves its value
    3. Now the browser makes a new request according the to value of location header as specified in the previous response. There is nothing special about this request. It is just a regular request. You can notice the url has changed to http://localhost:8080/ServletsJSPExamples/Hello.jsp
    4. The new request resource, in our case, Hello.jsp serves the response to browser.
    5. Thus, total 2 requests are made from browser.

 

 

 

 

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

One thought on “request.getRequestDispatcher and response.sendRedirect

  • February 17, 2016 at 11:52 pm
    Permalink

    good explanation sir

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *