Thursday, May 9, 2013

Difference between RequestDispatcher and response.sendRedirect()

Using RequestDispatcher, we can send request to a resource (html,servlet or jsp) which is available in same application or different application running on the same server.

Suppose a resource (/requestR) is available in different application (ServletApp2) running on the same server, Create a project 'ServletApp' with a servlet, RequestDServlet.


To send request to a resource available in same server different application, we need to get the context path of that applicatio( ServletApp2 ).

Once we got the context path, we can get the RequestDispatcher object to send request to the resource (/requestR).

configure the servlet  in web.xml


Now create another project with the name 'ServletApp2' with a servlet RequestRServelt.


and configure the servlet in web.xml of ServletApp2


Now deploy both applications ServletApp and ServletApp2 in the same server.

Once we run the application ServletApp, we are able to forward the request from a resource '/requestD' to a resource 'requestR' available in different application of same server.

Note: In a security conscious environment, the servlet container may return null for a given URL , i.e we can't get the context path of other applications

If resource available in different server: 


Incase if the resource to which request has to be sent, is available in a different application which runs in a different server, then RequestDispatcher will not work to send the request.

response.sendRedirect("location"):


HttpServletResponse provides a method to redirect to any location within the project or outside the project.

response.sendRedirect("location"), will take a string parameter location which is the relative or absolute path of the resource to which request has to be redirected.

Change the RequestDServlet with sendRedirect() code,


Once if we run the application , request will be redirected to ServletApp2 application's resource (/requestR).

As part of location, we can give relative path as well as absolute path.

Difference between RequestDispatcher.forward() and response.sendRedirect():

Using RequestDispatcher, we can forward or include the request to a resource available in same application or difefrent application available in same server.

Using response.sendRedirect(), we can redirect the request to a resource available in same application or different application in same server or different server.

If the resource is available in different server , we can redirect the request by using 
response.sendRedirect("http:// ip: port/ Application name/Resource name")




1 comment: