In this article, we are going to understand how to include an output from another Servlet into the current Servlet using the include() method of
RequestDispatcher object.
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 with the include() method we can include the contents of 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 all the methods provided by
ServletContext is
javax.servlet.RequestDispatcher.
How to create an object of RequestDispatcher
By calling getRequestDispatcher() method of ServletRequest.
By Calling getRequestDispatcher() method of ServletContext
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 include the request from another Servlet to the current Servlet?</b>
<br/>
<br/>
<br/>
<form action = "FirstServlet">
<input type = "submit" value = "Yes, let's do it!" />
</form>
</body>
</html>
Using RequestDispatcher to forward a request
We are creating a Servlet extending GenericServlet abstract class.
GenericServlet class implementsServlet and ServletConfig interface, hence
we can directly call the methods of ServletConfig within this Servlet.
We have implemented the service(ServletRequest req, ServletResponse res) of GenericServlet. Within service() method,
by using the request we have called its method
getRequestDispatcher(String path) method to create an object of RequestDispatcher.
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 to another Servlet named SecondServlet, as mentioned 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 include the content of another servlet named -SecondServlet
RequestDispatcher reqDispatch = request.getRequestDispatcher("SecondServlet");
//Using RequestDispatcher include() method to include the content of another Servlet in this Servlet.
reqDispatch.include(request,response);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<b>Executing the first servlet</b>");
}
}
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 <i>include()</i> method of RequestDispatcher object</h2>");
out.println("<b>Executing the second servlet</b> <br/> <br/>");
//Reading all the parameters
out.println("<b> Reading all the parameter and their values </b> <br/>");
Enumeration enum1 = getInitParameterNames();
while(enum1.hasMoreElements())
{
String paramName = (String)enum1.nextElement();
String paramValue = getInitParameter(paramName);
out.println("Parameter "+ paramName + " has a value " + paramValue);
out.println("<br/>");
}
}
}
Advertisement
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 RequestDispatcherInclude 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 full 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 Servlet, Hence -
We have named this URL FirstServlet. to access the first servlet, MyServlet1.java
We have named this 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 class by entering the command at the folder where you've stored the Servlet class file.
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 and press the submit button, if he/she wants to include
the contents of another Servlet named SecondServlet in this Servlet named FirstServlet, in web.xml.
Although this webpage calls the FirstSServlet but the this Servlet immediately calls the second servlet due to a call to RequestDispatcher's include() method to include its content.
As soon as the user clicks the button Let's do it, the request goes from the Servlet named FirstServlet to the Servlet named SecondServlet.
Difference between include() and forward() method
The Sevlet named FirstServlet calls the SecondServlet using the include() method and you see both the contents of SecondServlet
and FirstServlet being dispalyed in the output because the response object is not destroyed once the SecondServlet has committed its output,
which wasn't the case when you call forward() method.
Because when we call a Servlet from within another servlet using the forward(ServletResponse, ServletRequest) method,
we also pass the ServletRequest and ServletResponse objects to the other Servlet
method and the response object is destroyed once the another Servlet commits the output. That's why the original Servlet i.e. FirstServlet
doesn't get to use the response object to send its response, to see how it happens read Request Dispatching by forward().