What is RequestDispatcher in Servlets?

What is RequestDispatcher in Servlets?


Communication is very needed between Servlets and Container. Towards this goal Servlet API comes with three interfaces. Following table gives the list and their functionality.

Interface Functionality Example with explanation and screenshots available at
ServletConfig Used to communicate with Container to read web.xml (meant for one servlet only) init-param Example using ServletConfig
ServletContext Used to communicate between all the servlets of the application (meant to share global data) Reading Context Parameter with Example
RequestDispatcher Used to communicate between two Servlets (meant to pass data in between) include Example and forward Example

Our focus here is on RequestDispatcher.

RequestDispatcher interface from javax.servlet package is used to communicate between two Servlets. It comes with two methods include() and forward().

Where RequestDispatcher can be used?

  1. Client requests for a Servlet (say, Servlet-A) on the server. But the Servlet-A does not have capability to fulfill the client requested information. Inturn, Servlet-A can forward the client request to another Servlet (say, Servlet-B) using RequestDispatcher. Or to put it another way, Servlet-A can process the client request half-way and pass the half-processed data to Servlet-B for further processing and sending to client the response. Here Servlet-B sends the response to client (here forward() method is used). Servlet-B can also be a HTML file or JSP file on the server.
  2. Another scenario is, Servlet-A has got a part of information (response) required by client and Servlet-B has got the remaining information. Now Servlet-A can get the remaining information from Servlet-B that is added in its own information and send to client. Here response is delivered by Servlet-A (here include() method is used).
  3. RequestDispatcher is used to link or call to another resource on the server in a Web application.
  4. RequestDispatcher is used to transfer value attributes to another resource on the server.
  5. RequestDispatcher is used to include or forward the client request to another resource.
  6. RequestDispatcher is used to transfer the execution control to another Servlet/JSP.

An object of RequestDispatcher interface can be obtained as follows.

1. RequestDispatcher ServletRequest.getRequestDispatcher(String path)
2. RequestDispatcher ServletContext.getRequestDispatcher(String path)

Difference of obtaining RequestDispatcher objects between the above two sources is fully explained in RequestDispatcher from ServletRequest and ServletContext.

Examples on RequestDispatcher

1. RequestDispatcher include Example

2. RequestDispatcher forward Example

Leave a Reply

Your email address will not be published. Required fields are marked *