This post simply mentions the key differences between them.
request.getRequestDispatcher and response.sendRedirect.
- 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.
- 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
- 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
- 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
- The new request resource, in our case, Hello.jsp serves the response to browser.
- Thus, total 2 requests are made from browser.