Forward and Include Request in servlet

Forward and include both are used in Servlet with RequestDispatcher interface and both methods accept objects of ServletRequest and ServletResponse interface.

  forward() method

This is most commonly used method with Servlet or any java based framework and it forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. This method allows one servlet to do preliminary processing of a request and another resource to generate the response..

forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.

Example of forward method :-


  include() method

As per servlet doc , include() method Includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence, this method enables programmatic server-side includes.

The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.

Example of include method :-