Difference between RequestDispatcher’s forward(ServletRequest request, ServletResponse response) and HttpServletResponse’s sendRedirect(String location)

  1. Home
  2. Blog
  3. Difference between RequestDispatcher’s forward(ServletRequest request, ServletResponse response) and HttpServletResponse’s sendRedirect(String location)

Difference between RequestDispatcher’s forward(ServletRequest request, ServletResponse response) and HttpServletResponse’s sendRedirect(String location)

Forward method of RequestDispatcher will forward ServletRequest and ServletResponse that it is passed to path that was specified in getRequestDispatcher(String somePath). Response will not be sent back to client and so client will not know about change of resource on server. This method is useful for communicating between server resources (servlet to servlet). Because request and response are forwarded to another resource, all request parameters are maintained and available for use. Since client does not know about forward on server, no history of it will be stored on client, so using back and forward buttons will not work. This method is faster than using sendRedirect as no network round trip to server is involved.

Example using forward:

protected void doGet(HttpServletRequest pRequest, HttpServletResponse pResponse)
throws ServletException, IOException {
  RequestDispatcher reqDispatcher = pRequest.getRequestDispatcher("resourcePath");
  reqDispatcher.forward(pRequest, pResponse);
}

sendRedirect(String somePath) method of HttpServletResponse will tell client that it should send a request to specified path. So client will build a new request and submit it to server, because a new request is being submitted all previous parameters stored in request will be unavailable. Client’s history will be updated so forward and back buttons will work. This method is useful for redirecting to pages on other servers and domains.

Example using sendRedirect:

protected void doGet(HttpServletRequest pRequest, HttpServletResponse pResponse)
throws ServletException, IOException {
  pResponse.sendRedirect("resourcePath");
}
Let's Share
Show Buttons
Hide Buttons