Tag Archives: RequestDispatcher

Difference between sendRedirect and forward

sendRedirect
when you do response.sendRedirect(“url”) a HttpResponse is send back to the browser with status code 301 and “location header” with a url that you passed as a value, when browser gets the response and  see the status code 301 it searches for the location header and then makes a new request to this url
With sendRedirect you can redirect the user to the resources outside the container in which your web app is deployed a common excample is during online payment you are redirected to payment gateways

forward
RequestDispatcher dispatcher=request.getRequestDispatcher(“new.jsp”);
dispatcher.forward(request,response);
with dispatcher you want to forward the user request to a new jsp to get it served while providing the new jsp with same request and response objects thus the new jsp will be able to get all the parameters that were requested.
you can forward the user request to any resource that are within the container and within the web app context

  • With forward it is the conatiner that does internal work browser or any other client is not involved and url not changes
  • With redirect a request is sent to browser and a new request to a new url is made again leading to change in url and involvement of the client
  • You can forward request only to the resources that are within the webapp context not across domain not across the containe
  • you can redirect a request across various domains and also to the resources that are not within the context of your web app

Once you commit the responce you can not do any of them neither a redirect nor a forward