RequestDispatcher class is mainly used to 'pass on' the current request to another program (servlet) and therefore allows 'chaining' of the programs.RequestDispatcher class is mainly used to 'pass on' the current request to another program (servlet) and therefore allows 'chaining' of the programs.
RequestDispatcher class is mainly used to 'pass on' the current request to another program (servlet) and therefore allows 'chaining' of the programs. A RequestDispatcher primarily contains two methods include() and forward(). include() method includes the response of another program while forward() method forwards the request of the current program to another one.
The forward() method of RequestDispatcher forwards the request and response objects of ServletRequest and ServletResponse interface respectively to the path specified in getRequestDispatcher(String path). The response is sent back to the client therefore the client does not know about this change of resource on the server. This method helps for communicating between server resources, (servlet to servlet). Since request and response objects are forwarded to another resource therefore all request parameters are maintained and available for use. Any code written after forward(request, response) method will not execute as the request is already forwarded. As the client is not aware about this forward on the server therefore no history will be stored on the client and as a result backward and forward buttons does not work. This method is faster as compared to using sendRedirect because no network round trip to the server and back is required.
This method includes the content of a resource in the response. The resource may either be a servlet, or a JSP page, or an HTML file. This method also enables programmatic server-side includes. The included servlet can't change the status code or set headers of the response, any attempt made to do so is ignored. This method can be called at any time. It can only use ServletOutputStream or Writer of the response object to write the information.