RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

forward, jsp, redirect, servlets

Solution

requestDispatcher - forward() method

When we use the `forward` method, 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.

When `forward` is called on the `requestDispatcher`object, 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.

Using the `forward()` method is faster than `sendRedirect`.

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

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 `sendRedirect` method is visible as a new request to the client.

In case of `sendRedirect` call, 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.

`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.

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

Problem

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

Original source

Related problems