RequestDispatcher vs sendRedirect
A Controller servlet can conclude either a forward or a redirect operation at the end of processing a request.
Here are the basic differences between a requestDispatcher's forward() and
sendRedirect() of the ServletResponse interface.
Forward
Since forward() method of RequestDispatcher is handled on the
server , therefore the request and its associated session are available to the
forwarded resource and you can pass data between them using request.setAttribute().
forward() separates the responsibilities for handling the requests among several
components. This method generally sends a request and response object to
resources (servlets or JSP's) of the same ServletContext.
You can also decide to forward to one page in one condition and a different
page in another. RequestDispatcher transfers control immediately whenever
the forward() method is called to the resource referenced by the
RequestDispatcher.
sendRedirect
sendRedirect() method of a response object sends the url to the browser that includes the parameter of sendRedirect() method
Browser treats this a new request from the client. sendRedirect() forwards a
requests to a resource outside of the current web application. Using
sendRedirect is similar to open a new browser and type your url. A sendRedirect()
also updates the browser history and transfers control only when the whole
service method completes. There is only one way to pass data is through the
session or using web parameters (url?name=value).
Note: Here are some more concepts that we must know:
- RequestDispatcher.forward() and PageContext.forward() are effectively the same. PageContext.forward is a helper method that calls the RequestDispatcher method.
- When you invoke RequestDispatcher.include(), the servlet engine transfers control of this HTTP request internally from your current servlet or JSP to another servlet or JSP or static file, while invoking response.sendRedirect() method sends an HTTP response to the browser to make another request at a different URL. In big applications, instead of forwarding to another servlet we generally use beans. Beans check a form, formats the response and returns to the servlet.