RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()
What is the conceptual difference between
requestDispatcher - forward() method
When we use the
forwardmethod, the request is transferred to another resource within the same server for further processing.
In the case of
forward, the web container handles all processing internally and the client or browser is not involved.
forwardis called on the
requestDispatcherobject, we pass the request and response objects, so our old request object is present on the new resource which is going to process our request.
Visually, we are not able to see the forwarded address, it is transparent.
forward()method is faster than
When we redirect using forward, and we want to use the same data in a new resource, we can use
request.setAttribute()as we have a request object available.
In case of
sendRedirect, the request is transferred to another resource, to a different domain, or to a different server for further processing.
When you use
sendRedirect, the container transfers the request to the client or browser, so the URL given inside the
sendRedirectmethod is visible as a new request to the client.
In case of
sendRedirectcall, the old request and response objects are lost because it’s treated as new request by the browser.
In the address bar, we are able to see the new redirected address. It’s not transparent.
sendRedirectis slower because one extra round trip is required, because a completely new request is created and the old request object is lost. Two browser request are required.
sendRedirect, if we want to use the same data for a new resource we have to store the data in session or pass along with the URL.
Which one is good?
Its depends upon the scenario for which method is more useful.
If you want control is transfer to new server or context, and it is treated as completely new task, then we go for
sendRedirect. Generally, a forward should be used if the operation can be safely repeated upon a browser reload of the web page and will not affect the result.