Tuesday, September 8, 2009

Redirect And Forward

Redirect Versus Forward

1. Redirect sends the request back to browser and all previous request context and parameters are lost and a new request will be send to redirected page.
Forward does the decorator work for the request and can add more parameters to the request and send to the forwarded page.
2. Redirect is slower than Forward
3. Redirect will show the redirected page URL in address bar. Forward will not.
4. On refresh, only redirected page will be called not the page which has redirected i.e. if the flow is from A to B then on refresh only B will be called.
But in case of forward, if the flow is A to B then on refresh First A and then B will be called in the same sequence as occurred before.
5. Redirect can be used to send the request to another running web application. Forward will work within a web application only.
6. Redirect is done when servlet’s service method get completed i.e. statements after redirect call will execute first and after completion of service method redirect will occur.
But forward does the work of a method call i.e. the statements after forward call be executed when the forwarded page has done its work.
Example with a code snippet.
FirstServlet.java
...
System.out.println("Before Next Page");
response.sendRedirect("NextServlet");
System.out.println("After Next Page");

In NextServlet.java
System.out.println("Next Servlet called....");

In this case following will be the output:
Before Next Page
After Next Page
Next Servlet Called

I.e. in case of redirect first servlet ‘s service method will complete and then next servlet is called..
Now if we could have used forward instead of sendRedirect then following will be the output
Before Next Page
Next Servlet Called
After Next Page

No comments:

Post a Comment