forward and sendRedirect

Whenever there is a request from the client (or browser) to the server, the server container creates two objects
1. request
2. response
and pass these objects to the servlet along with other parameters if needed.
 
 S.No.  RequestDispatcher.forward  HttpServletResponse.sendRedirect
 1. the request is forwarded to other resource(say B) in the same context, B does some work and sends response back to the browser  When browser makes request to resource A , resource A does something and then send response code 301 or 302 to the browser along with the URL for resource B in Location field of the HTTP response header. The browser will make a new request for resource B
 2.  The bowser has no knowledge that the forward took place. The Address Bar of the browser still contains the same url of resource A.  The Address Bar of the browser will display the URL of resource B
 3.  The entire process takes place within one request/response cycle.Hence same request and response objects are forwarded to resource B  The request and response objects that are passed to resource A will be discarded and container will create the new request and response objects
 4.  The request can’t be forwarded ouside of the context i.e you can’t forward the request to the resources of other application.  using sendRedirect method, the resources of the other application can be accessed.
 5.  The forward method is faster because it involves fewer trips between the browser and the server The sendRedirect method is slower. 
Rate this post

Leave a Reply