RequestDispatcher forward() Example

Communication between the Servlets is an important task to the Programmer. To achieve this, 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() and RequestDispatcher forward(). 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.

The include() method is covered in RequestDispatcher include Example with realtime scenarios, coding examples and explanation in length. Now let us see about forward() method right now.

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 forward() Method

When to use RequestDispatcher forward() method?

Client calls a Servlet for some information. But the Servlet cannot honour the request because it is incapable. But it knows that another Servlet exists which can do the job of the client. Then how the first Servlet (called by the client) can send (forward) the request to another Servlet. Here, forward() method of RequestDispatcher is used.

That is, client calls one Servlet (say S1) but response goes from another Servlet (say S2). Ofcourse, the client is not aware of all this affairs happening on the server.

Here, response of S2 goes to client but never of S1. Remember, in include() method both S1 and S2 goes.

Some realtime scenarios to use RequestDispatcher forward() method.

  1. USA Population: I call a servlet on an Indian server (which can give India population) to fetch me the population of USA. But the Servlet on the Indian server cannot but it knows the address of a Servlet on the USA server that can fulfill the client request. Instead of telling sorry, the Indian Servlet can send a message to USA Servlet to honour the client request with forward() method.
  2. Order Format: The client sends an order to a company for some goods by calling a Servlet (say S1). But it is not in the format required by the Sales department. S1 Servlet would like to forward the client request to another Servlet (say S2) that can convert the client data into the correct format. To pass the client request to S2, S1 uses forward() method.
Example on RequestDispatcher forward() method

In the following example code, client sends two numbers to a Servlet to know their product. It calls a Servlet GetMe (with alias name S1 in web.xml). S1 forwards the client request to Product Servlet (of alias name S2) using forward() method of RequestDispatcher interface.

Client Program: TwoNumbers.html


Product of Two Numbers

Enter First Number
Enter Second Number

S1 is the alias name of GetMe Servlet which the client calls.

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


  snrao1
  GetMe



  snrao1
  /S1



  snrao2
  Product



  snrao2
  /S2

Now let us write the GetMe servlet.

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

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

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

    out.println("Hello 1");      // Hello 1 will not go to client

                                 // create an object of RequestDispatcher
    RequestDispatcher rd = req.getRequestDispatcher("/S2");   // S2 is the alias name of Product servlet
    
                                 // send the client data of two numbers available with req of S1 (GetMe) to req of S2 (Product) with forward()
    rd.forward(req, res);        // after seeing output, replace with rd.include(req, res) and see change in output
                                 // you can learn yourself the difference between rd.include(req, res) and rd.forward(req, res)

    out.println("Hello 2");      // Hello 2 will not go to client
    out.close();
  }
}

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

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

public class Product 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");
    double num1 = Double.parseDouble(str1);
                                 
                                 // for second number, above two steps in one step
    double num2 = Double.parseDouble(req.getParameter("t2"));   

                                // now left is multiplication
    double result = num1 * num2;
                                 
                                 // prepare response.  This response will go to the client directly (and not to S1)
    out.println("Your first number: " + num1);  
    out.println("
Your second number: " + num2); out.println("
Their product is " + result); out.close(); } }

Now what client will receive and will not receive:

// response of S1 (GetMe Servlet) not received
      out.println("Hello 1");

// response of S2 (Product Servlet) will be received
    out.println("Your first number: " + num1);  
    out.println("
"Your second number: " + num2); out.println("
Their product is " + result); // response of S1 (GetMe Servlet) not received out.println("Hello 2");

That is, response of S1 never goes to the client and only S2 goes (eventhough Hello 1 exists before calling forward() method in GetMe Servlet). Following figure explains.

RequestDispatcher forward()

Observe the figure. Client request (or calls) the Servlet S1. S1 sends client data to S2 with forward() method. Response of S2 goes directly to client.

Let us see the screens.

Client Program: HTML file, TwoNumbers.html, when fields are filled up and clicked submit button.

RequestDispatcher forward()

Output screen.

RequestDispatcher forward()

Observe the output. The output (response) of S2 (Product Servlet) only goes to client but not of S1 (GetMe Servlet). Hello 1 and Hello 2 of S1 are not displayed in the output screen.

9 thoughts on “RequestDispatcher forward() Example”

  1. “JSPs are more useful for generating output. Justify with usage of requestDispatcher() and appropriate example”. I want this question’s answer.. can u explain me this answer..

  2. “Some realtime scenarios to use include() method” In this line it should not be include() instead it should be forward()

Leave a Comment

Your email address will not be published.