Difference between forward and Redirect
Control can be forward to resources available within the server from where the call is made.
This transfer of control is done by the container internally and browser / client is not involved. This is the major difference between forward and sendRedirect.
When the forward is done, the original request and response objects are transfered along with additional parameters if needed.
Control can be redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container.
That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser.
Then the browser initiates a new request to the given url. Since it is a new request, the old request and response object is lost.
For example, sendRedirect can transfer control from
http://javaskool.com to http://anydomain.com but forward cannot do this.
and like during booking ticket url is redirected from booking agent to some payment getway.
‘session’ is not lost in both forward and redirect.
To feel the difference between forward and sendRedirect visually see the address bar of your browser, in forward,
you will not see the forwarded address (since the browser is not involved) in redirect, you can see the redirected address.
When can we use forward and when can we use sendRedirect?
Technical scenario: redirect should be used
1. If you need to transfer control to different domain
2. To achieve separation of task.
For example, database update and data display can be separated by redirect.
Do the PaymentProcess and then redirect to displayPaymentInfo.
If the client refreshes the browser only the displayPaymentInfo will be done again and PyamenProcess will not be repeated.
But if you use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.
For other than the above two scenarios, forward is efficient to use since it is faster than sendRedirect.
Example for forward and sendRedirect based on real world
Consider the real world scenario, the milk man comes and asks for monthly payment to you in your house. Here house is the container and you are a resource existing in the container. Milk man is the client or browser.
He asks for the monthly payment to you, this is the request made by the browser to resource A.
If you go inside your house and ask your mother (another resource B inside the same container) for the cash and come back and deliver to milkman this is called forward.
If you ask the milkman to speak himself to your mother inside your house or you ask the milkman to speak to your father who is in his office (different domain) then this is called redirect.