Difference between sendRedirect() and forward() in jsp servlet Java? - Java @ Desk

Thursday, July 18, 2013

Difference between sendRedirect() and forward() in jsp servlet Java?

sendRedirect() and forward() methods are applicable to both servlets and jsp in java. Since jsp converts to a servlet itself, these methods can be used inside a scriplet in a jsp.

sendRedirect():
This method is called from HttpServletResponse object. This method from response object expects an URL where the response is required to redirect. This sends the user to different location located on a different server altogether. This happens on a client side or browser. The new address will be visible in the browser.

Redirect sets the response status to 302, and the new url in a Location header, and sends the response to the browser. Then the browser, according to the http specification, makes another request to the new url.

The most general example of redirect is the payment gateway. Most of the application tie up with the third party merchant payment gateways. So when an order placed by the customer is done and the following step is to do the payment, the application redirects the browser to altogether new location payment gateway.

Redirect goes to the browser in form of a 301 response and then gets back redirected using Location header.

forward():
This method is called from RequestDispatcher Interface.
forward(ServletRequest request, ServletResponse response)

This method sends the client request on to different resource within the same web application for further processing. The new resource could be any servlet or jsp within the application. This happens on a server side.

Below are the differences in terms of interview language:

sendRedirect() forward()
In this case, request gets transferred to resource outside the application In this case, request gets transferred to resource within the application
This happens on the client side This happens on the server side
New URL of some other web application will appear in the browser URL of the same web application remains on the browser
In this case, existing request and response objects are lost In this case, existing request and response objects are preserved
Classic example, some sort of advertisement on the web page Call another servlet o jsp within the application







1 comment: