Search code examples
jsphttp-redirectservletsforward

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()


What is the conceptual difference between forward() and sendRedirect()?


Solution

  • ##requestDispatcher - forward() method##

    1. When we use the forward method, the request is transferred to another resource within the same servlet for further processing. It is strictly a 'internal redirect'
    1. In the case of forward, the web container handles all processing internally and the client or browser is not involved.
    1. When forward is 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.
    1. Visually, we are not able to see the forwarded address, it is transparent.
    1. Using the forward() method is faster than sendRedirect.
    1. 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.

    ##SendRedirect##

    1. In case of sendRedirect, the request is transferred to another resource, to a different domain, or to a different server for further processing.
    1. When you use sendRedirect, the container transfers the request to the client or browser, so the URL given inside the sendRedirect method is visible as a new request to the client.
    1. In case of sendRedirect call, the old request and response objects are lost because it’s treated as new request by the browser.
    1. In the address bar, we are able to see the new redirected address. It’s not transparent.
    1. sendRedirect is 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.
    1. But in 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.

    Source