RequestDispatcher include() Example


Communication (passing data in between) is an important concept in computers and for this Servlets is no exception. Towards this goal, we studied reading private data of a servlet and reading global data by all servlets. Now let us see how to pass data between two servlets (one-to-one) and for this Servlet API comes with javax.servlet.RequestDispatcher interface.

When to use RequestDispatcher interface?

RequestDispatcher is used in two cases.

  1. To include the response (output) of one servlet into another (that is, client gets the response of both servlets).
  2. To forward the client request to another Servlet to honour (that is, client calls a Servlet but response to client is given by another Servlet).

How many methods exist in RequestDispatcher interface?

Only two methods exist. RequestDispatcher include() method and the other is forward() method. Let us see what Servlet API says about these methods.

  • void include(ServletRequest request, ServletResponse response) throws ServletException, IOException: Includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence, this method enables programmatic server-side includes.
  • void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException: 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.

Observe, the parameters of both methods is the same of objects of ServletRequest and ServletResponse.

This tutorial covers RequestDispatcher include() method and the later postings cover the other forward() method and the difference of two.

How to obtain an object of RequestDispatcher interface?

For this two styles exist – using ServletRequest object and ServletContext object. getRequestDispatcher(String path) method returns an object of RequestDispatcher and the same method exist in both interfaces of ServletRequest and ServletContext. Small difference in the usage exist between the two and we see later. In this posting, ServletRequest is used.

Let us see what API says about getRequestDispatcher(String path) method:

  • RequestDispatcher getRequestDispatcher(String path): Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. A RequestDispatcher object can be used to forward a request to the resource or to include the resource in a response. The resource can be dynamic or static.

RequestDispatcher include() Method

When to use RequestDispatcher include() method?

To place (include) the response content (ouput) of one servlet into another servlet’s response. That is here, client gets the response of both servlets. Or simply to say, to put the output of one servlet into another.

Some realtime scenarios to use RequestDispatcher include() method.

  1. Login Validation: Suppose a project involves a few login screens developed by different programmers; ofcourse, every programmer uses the same standard user name and password as per the guidelines of Project Manager. Any small change in the logic should be affected in each programmer’s servlet. To overcome this, let us plan a central servlet (I call it as S2) to validate the login data. Now client calls a servlet (I call it as S1) developed by a Programmer. The Programmer sends the client data (actually coming to S1) to S2 for validation. The S2 servlet validates the data and send back the result of validation (as response) to S1. Now S1 sends the result of validation to client.
  2. Electrical Billing: Another is Electricity consumption billing. The bill collector takes the latest meter reading and sends to a servlet (along previous reading), say S1 for billing. The S1 servlet does not have any code to estimate the bill amount, but knows that servlet S2 is capable. S1 passes the client data to S2. S2 will estimate, prepares the bill and send to S1. S1 inturn, sends to client.
    Once you satisfy with this task, I add a small spice. Where is the rate per unit of power consumed? Obviously, it must be with S2 because it is estimating. No, but the rate is available with S1. Now S1 has three responsibilities – a) to send actual client data (of two readings, previous and latest) as it is to S2 b) to send rate per unit to S2 (remember this is extra information of S1 which not coming from client) and c) to receive the response of S2, add its own response, if any, like last date of bill payable etc to client. This posting does this job.
To accomplish the above second realtime example, let us write the code on RequestDispatcher include().

Client Program: Electricity.html


Electrical Billing

Enter Latest Reading
Enter Previous Reading

S1 is the alias name of Accounts servlet which the client calls.

Following is the web.xml entry for the two servlets.


  snrao1
  Accounts



  snrao1
  /S1



  snrao2
  Billing



  snrao2
  /S2

Now let us write the Accounts servlet.

The First servlet – File Name: Accounts.java (alias name S1 in web.xml)

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class Accounts extends HttpServlet
{
  public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  {
    res.setContentType("text/html");    
    PrintWriter out = res.getWriter();

    out.println("Following are your Bill Particulars

"); // attach rate per unit of power to req object req.setAttribute("unitRate", new Double(8.75)); // create an object of RequestDispatcher RequestDispatcher rd = req.getRequestDispatcher("/S2"); // S2 is the alias name of second Servlet, Billing // send the client data available with req of S1 (Accounts) to req of S2 (Billing) with include() rd.include(req, res); // add extra information to req of S1 to be sent to client out.println("

Please pay the bill amount before 5th of every month to avoid penalty and disconnection"); out.close(); } }

The Second servlet – File Name: Billing.java (alias name S2)

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class Billing extends HttpServlet
{
  public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  {
    res.setContentType("text/html");    
    PrintWriter out = res.getWriter();

   			         // extract the client data from req object.  Infact, this is actually to be done by S1 
    String str1 = req.getParameter("t1");
    int latestReading = Integer.parseInt(str1);
                                 
                                 // for previous reading, above two steps in one step
    int previousReading = Integer.parseInt(req.getParameter("t2"));   

                                 // read rate per unit from req object
    Object obj = req.getAttribute("unitRate");
    Double d1 = (Double) obj;
    double rate = d1.doubleValue();

		                 // now left is to prepare the bill
    int noOfUnits = latestReading-previousReading;
    double amountPayable = noOfUnits * rate;
                                 
                                 // prepare response.  This response is added to S1 response
    out.println("Previous reading: " + previousReading);  
    out.println("
Current reading: " + latestReading); out.println("
Bill Amount Rs." + amountPayable); } // do not close out object }

Now what client will receive:

// response of S1 (Accounts servlet)
      out.println("Following are your Bill Particulars

"); // response of S2 (Billing servlet) out.println("Previous reading: " + previousReading); out.println("
Current reading: " + latestReading); out.println("
Bill Amount Rs." + amountPayable); // response of S1 (Accounts servlet) out.println("

Please pay the bill amount before 5th of every month to avoid penalty and disconnection");

The order is also maintained. Following figure explains.

RequestDispatcher include()

Observe the figure. Client request (or calls) the servlet S1. S1 sends client data to S2 with include() method. Response of S2 comes to S1. S1 sends to client its response (of S1) and also of S2.

Let us see the output screens.

Client Program: HTML file Electricity.html when fields are filled up.

RequestDispatcher include()

Output screen.

RequestDispatcher include()

Observe the output and its order. The client receives the response of both S1 (Accounts) and S2 (Billing).

With this understanding of include() method, read forward() also, see right side series. OR You can modify this program with only one line code change. Replace, rd.include(req, res) with rd.forward(req,res) in Accounts Servlet. See the difference in output screens.

6 thoughts on “RequestDispatcher include() Example”

  1. One small correction (I saw it happen this way in my example!):

    After include() call, it goes to s2, adds the response of s2 to already generated response of s1.

    After that, it doesn’t come back to s1 to add the remaining part of the response, it directly goes back to the client.

    Thanks,
    Navin

  2. Really dis website person did a great job actually i searched for a detailed information for RequestDispatcher maybe we can say it as excact(correct) explanation of RequestDispatcher include and forward method i googled many websites but dis s d ly website i got full satisfied for RequestDispatcher explanation and too with programs.

  3. sir,

    How i have to configure in web xml in myeclipse for two servlets..?? am not getting the same program output in myeclipse

    this is my html form tag.what i need to do in web xml for mapping URL pattern.please help

Leave a Comment

Your email address will not be published.