> Exact Difference between jsp:forward and RequestDispatcher.sendRedirect
Correction ..
Its response.sendRedirect and not RequestDispatcher.sendRedirect
Ok ..I'll tell u 6 differences ...
1) In forward mechanism the request is forwarded from server to server .i.e the request objects are posted internally within the server and hence client [browser] is not involved.
In sendRedirect communication is sent to the browser to redirect its request and thus makes a round trip with the browser.
2) Forward is much faster in performance compared to redirect due to no round trip with browser and because no headers are sent to the browser.
3) In forward the URI does not change. However in redirect, the URI is changed.
4) Forward will not work in a different servlet context. Ex: U cant forward requests from Yahoo.com to java.sun.com
Redirect works in both same/ as well as different contexts.
5) Forward retains the request, but with redirect all request parameters are lost.
6) U need to provide the complete URI during redirect Ex: "http://...."
but with forward only relative path is sufficent.
did I miss any other difference ;-)
By the way this used to be a common question I used to ask around 3 yrs back to newcomers[1-2 yrs exp] while conducting interviews in my company.
Regards
-Rohit Kumar
> i only thought of redirect makes new request to the
> server and forward retains the request and goes to
> another page
Almost. A forward does indeed retain the request because a forward is performed on the server: control is simply passed to another resource while a redirect is performed by the browser. A redirect will change the URL and will also end up in the page history, a forward does not.
My mistake on point# 6 ..tx
But one needs to be careful when writing the url.
Ex ..I have "/code" as my web application context path :-
A.jsp :
<jsp:forward page="/jsp/backend/login.jsp" />
<%
System.out.println("Hello world .. forward test ;-)");
%>
B.jsp :-
<%
response.sendRedirect("/code/jsp/backend/login.jsp");
System.out.println("Hello world ..redirect test ;-)");
%>
So in A.jsp if we add the context root then this forward will fail ...
<jsp:forward page="/code/jsp/backend/login.jsp" />
Similarly in B.jsp if remove the application context path then this will fail ..
response.sendRedirect("/jsp/backend/login.jsp");
Now a question to U :
QUES: Will "Hello world .. forward test ;-)" be printed ?
What about "Hello world ..redirect test ;-)" ?
Its a simple question ..I'll reply the answer if no one posts by tomorrow morning.