In this article, we are going to understand how to dispatch a request from one servlet to another servlet by using the
RequestDispatcher object. This helps when the request processing or the response generation has to be shared between multiple servlets.
An application could be served by many servlets which are configured in a deployment descriptor file, web.xml. Using this configuration file with the
RequestDispatcher object we can -
Forward the current request from one servlet to another servlet.
Include the response from another servlet in the current servlet.
RequestDispatcher is an interface and it is a part of the Servlet API. The full path to import and
access the methods of RequestDispatcher is
javax.servlet.RequestDispatcher.
How to create an object of RequestDispatcher
By calling the getRequestDispatcher() method of ServletRequest.
By calling the getRequestDispatcher() method of ServletContext.
RequestDispatcher methods
Let's take a look at the methods part of javax.servlet.RequestDispatcher interface.
This method includes the contents of another Servlet, JSP or static HTML page in the response.
Creating a webpage which calls the Servlet
We are creating a webpage which asks the user to click a button named Yes, let's do it!,
which when clicked dispatches or forwards the current request from the servlet named FirstServlet in the deployment descriptor file(web.xml).
Webpage1.jsp
<html>
<head>
<title> ServletRequest Demo </title>
</head>
<body>
<b>Do you want to forward the request from first servlet to the second servlet?</b>
<br/>
<br/>
<br/>
<form action = "FirstServlet">
<input type = "submit" value = "Yes, let's do it!" />
</form>
</body>
</html>
Advertisement
Using RequestDispatcher to forward a request
In the upcoming example, we are creating a servlet by extending the GenericServlet abstract class.
GenericServlet class implements the Servlet and ServletConfig interfaces, hence
we can directly call the methods of ServletConfig within this servlet.
First, we have implemented the service(ServletRequest request, ServletResponse response)
method of GenericServlet. Within the service() method,
we have used the available request object of ServletRequest, to call its method
getRequestDispatcher(String path), which creates an
an object of RequestDispatcher.
Next, by using this object of RequestDispatcher, we are going to call its method
forward(ServletRequest req, ServletResponse res),
to forward the current request from the current servlet named FirstServlet(MyServlet1.java) to another servlet named SecondServlet(MyServlet2.java), by specifying them in the deployment descriptor file(web.xml)
MyServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class MyServlet1 extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
//Creating an object of RequestDispatcher to forward the request to another servlet named - SecondServlet
RequestDispatcher reqDispatch = request.getRequestDispatcher("SecondServlet");
//Using RequestDispatcher forward() method to forward the current request and response to another servlet.
reqDispatch.forward(request,response);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h2>Using RequestDispatcher object</h2>");
out.println("The first servlet");
}
}
MyServlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class MyServlet2 extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h2>Using RequestDispatcher object</h2>");
out.println("The second servlet");
}
}
Directory Structure of Servlet files
The diagram above depicts how to arrange the servlet files in a specific directory structure, as per Java Servlet Specification-
Project Folder - We have created a project folder named RequestDispatcherEx within
the webapps folder of Tomcat installation folder. This folder contains the servlet class(.java) file and WEB-INF folder.
WEB-INF - Within your project folder, you create another folder named WEB-INF and this folder should contain the deployment descriptor file(web.xml) of your Java Servlet program.
classes - Within the WEB-INF folder you should create a folder named classes. This folder should contain the compiled(.class) form of your Java Servlet class.
Creating the Deployment Descriptor file
As per the Java Servlet specifications, every web application based on Servlet must have a Deployment Descriptor file(an XML file) named web.xml.
So, let's create one -
In deployment descriptor file, <servlet> has two child tags <servlet-name> and <servlet-class> :
<servlet-name> tag is used to specify a unique name for our servlet class.
<servlet-class> tag is used to specify the fully qualified name of the servlet class.
Note:
The child tag <servlet-name> of <servlet> tag is matched with the <servlet-name> child tag of
<servlet-mapping>. The
<url-pattern> child tag is used to specify the URL to access the Servlet, Hence -
We have named a URL, FirstServlet. to access the first servlet, MyServlet1.java
We have named a URL, SecondServlet to access the second servlet, MyServlet2.java.
Setting the classpath
Much of the support for developing the web applications based on the Java Servlet technology does not come with the core Java.
Hence, in order to compile the Servlet programs, we have to set the classpath to a jar file named
servlet-api.jar.
This jar file provides all the classes that are required for the Servlet programming and it comes within the lib Folder of
Tomcat installation folder.
For example, in our case we have installed Tomcat Web Server within the C: Drive, hence the path to our lib folder containing the servlet-api.jar is - C:\apache-tomcat-9.0.2\lib
There are two ways to set the classpath -
You could set the classpath by entering this command at the Command Prompt, but this only temporarily sets the classpath to the path of servlet-api.jar file. If you restart your system, you will have to set the classpath again.
set classpath=C:\apache-tomcat-9.0.2\lib\servlet-api.jar
In order to set the classpath permanently, you need to set your classpath system variables. A simple tutorial on how to permanently set the classpath system variables, you may read
How to permanently set the classpath system variable
Compiling the Servlet class
After setting the classpath, you need to compile the both of the servlet classes by entering the following commands at the folder where you've stored the servlet classes.
javac -d WEB-INF/classes MyServlet1.java
javac -d WEB-INF/classes MyServlet2.java
Executing the Servlet
First we execute the webpage containing the form, asking the user to press the Let's do it! button, if he/she wants to forward
the current request from the first servlet to
the second servlet.
As soon as the Let's do it! button is pressed, this webpage calls the first servlet,
but this first servlet immediately calls the second servlet due to a call to RequestDispatcher's forward() method.
In other words, as the user clicks the button Let's do it, the request goes from the servlet named FirstServlet
to the servlet named SecondServlet and the user is presented a response from the second servlet, as shown below.
Note:
Although the servlet named FirstServlet calls the SecondServlet, you will see only the output of SecondServlet,
while the output from the FirstServlet won't be displayed. Why?
Because, when we call the second servlet from within the first servlet by using the forward(ServletResponse, ServletRequest)
method,
we also pass the ServletRequest and ServletResponse objects to the second servlet
method, and the response object is destroyed once the second servlet commits the output. That's why the first servlet i.e. FirstServlet
doesn't get to use the response object to send its response.