Friday, October 07, 2005

Difference between response.sendRedirect and requestDispatcher.forward with respect to session?


When you forward the request with requestDispatcher.forward the target servlet/JSP share the same session. But with sendRedirect the session information is not preserved. ( target is not in scope of session)

A RequestDispatcher forward is a server side activity. So the request and its associated session are available to the forwarded resource.

If you use sendRedirect to redirect the user to a different context, i.e. a different application, of course the session information is not preserved. It would be meaningless because sessions are tied to a specific context. (for example, my session information from javaranch would have no meaning if I decided to go to yahoo)

However, using sendRedirect within the same context works perfectly.

You might have a scenario in which you want to redirect the request to a different URL, but still want to use a session. There is a special URL encoding method just for that:

response.encodeRedirectURL("/resourceName");

Remember to include the slash in the method.

0 Comments:

Post a Comment

<< Home