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?
- 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.
- 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).
- RequestDispatcher is used to link or call to another resource on the server in a Web application.
- RequestDispatcher is used to transfer value attributes to another resource on the server.
- RequestDispatcher is used to include or forward the client request to another resource.
- 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