Friday, October 07, 2005

Difference between response.sendRedirect and requestDispatcher.forward?

A RequestDispatcher does the work on the server side. That’s the big difference between a redirect and a request dispatch - Redirect makes the client do the work, here client is the browser not the user. RequestDispatch makes something else on the server do the work. The something else is nothing but a resource in the Web Application which should be either a Servlet Or a JSP

A forward passes the current request along to a new resource within the same context. Request parameters and scoped variable are therefore preserved.

A redirect causes a new request to be issued by the browser. Hence request parameters and request scoped variables are not preserved. Context(or)Application and Session scoped variables are indeed preserved. As context attributes are accessible to all request and session attributes are accessible for any request from the same client. Redirect can be used to transfer the control to a different context.

A sendRedirect sends the mentioned url to the browser and the browser sends a new request to that url. Request parameters and scoped variables are therefore NOT preserved. sendRedirect is typically used to forward requests to a different context (Application Context).

Another difference would be if we use RequestDispatch there will be no URL change in the browser as the request is dispatched within the same Web App, whereas if we use sendRedirect the user sees the new URL in the browser. This is because the browser makes the new call on the user’s behalf after the originally requested servlet returns the requested resource URL. With sendRedirect the new URL is exposed to the user and the client has the ability to bookmark the page.

Also when switching protocols like from Http to Https, we use sendRedirect.

Remember:

Redirect = Client

RequestDispatch = Server

Learn more redirect Here

0 Comments:

Post a Comment

<< Home