File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes servlets Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "servlets" Watch "servlets" New topic


kiran keshoju

Joined: Oct 21, 2004
Posts: 1
What is the difference between sendRedirect() and forward() in servlets
Shailesh Chandra
Ranch Hand

Joined: Aug 13, 2004
Posts: 1082

sendRedirect occurs at the client side. So it is more or less equals to the client typing the new URL in his address of the browser.

In other words browser is asked to request a url

This takes a greater turn around time i.e. the new URL will be invoked from the client.

forward is transparent to the user and he doesn't know that there has been some forward to other url. This is a server side redirection and infact takes lesser turn around time

Gravitation cannot be held responsible for people falling in love ~ Albert Einstein
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

One thing that was not mentioned is the intent of each of the calls. I recommend searching the forum for a more complete outline, but it important to realise that these are different pieces of functionality and are not necessarily interchangeable.

Take as an example two common pieces of functionality.

The first is to display an error page when some processing fails. In this case, you can put any additional information on the request, forward to the display page, and everything works fine. The client's browser still has the same URL so if they reload the page it will repeat the previous step.

The second is to submit some data then send back to a menu. If you use forward, the URL doesn't change, so if the user refreshes the screen it resubmits the data! In this case, it is better to process the data then sendRedirect to the menu page. This forces the client to send a second HTTP request, asking for the menu page.

In the first example, if you use sendRedirect rather than forward you can't place information on the request context, and information gets lost once the new request comes in. You could place the information on the session and still use sendRedirect, but placing request-scope data on the session is a recipe for disaster. This is another story.

Hope this helps,
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
thanks Bartender, I have never thought of it. its really worth reading.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: servlets
It's not a secret anymore!