Java Servlet RequestDispatcher Tutorial
Communication between the Servlets is an important task to the programmer. Request Dispatcher is an interface whose implementation defines an object which can dispatch the request to any resources on the server. In this tutorial, we will see how the javax.servlet.RequestDispatcher
interface is used to forward or include the response of a resource in a Servlet.
Table Of Contents
1. Introduction
Servlet Request Dispatcher is an interface whose implementation defines that an object can dispatch requests to any resource (such as HTML, Image, JSP, Servlet etc.) on the server. Another advantage of this interface is that it is used in two cases:
- To include the response of one Servlet into another (i.e. the client gets the response of both Servlets)
- To forward the client request to another Servlet to honor the request (i.e. the client calls a Servlet but the response to client is given by another Servlet)
This interface is placed in the javax.servlet
package and has the following two methods:
Method | Description |
---|---|
public void forward(ServletRequest request, ServletResponse response) throws IOException, ServletException | This method forwards a request from a Servlet to another resource (i.e. Servlet to Servlet, Servlet to JSP, Servlet to HTML etc.) on the server and there is no return type |
public void include(ServletRequest request, ServletResponse response)throws ServletException, IOException | This method includes the content of a resource in the response and there is no return type |
1.1 Difference between forward() and include()
Both the methods are a part of Request Dispatcher interface. These methods will accept an object of the Servlet request and response interface. The main difference is that when a programmer uses forward, the control is transferred to the next Servlet or JSP the application is calling while in the case of include, the control retains with the current Servlet and it just includes the processing done by the calling of Servlet or the JSP.
1.1.1 Request Dispatcher forward() Method
In the below conceptual figure, the response generated by the Servlet2 is visible to the user, but the response generated by the Servlet1 is not visible to the user.
1.1.2 Request Dispatcher include() Method
In the include
method concept, the response of the Servlet2 is included in the response of the Servlet1 and the generated final response is sent back to the client.
1.2 How to get the object of RequestDispatcher?
The getRequestDispatcher()
method of the Servlet Request interface returns the object of the Request Dispatcher.
Syntax
RequestDispatcher rs = request.getRequestDispatcher("hello.html");
After creating the RequestDispatcher
object, developers will call the forward()
or include()
method as per the application’s requirement.
rs.forward(request,response);
Or
rs.include(request,response);
Now, open up the Eclipse Ide and let’s see how the RequestDispatcher
interface is used to forward or include the response of a resource in a Servlet!
2. Java Servlet RequestDispatcher Tutorial
Here is a step-by-step guide for implementing the Servlet framework in Java.
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.
2.2 Project Structure
Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.
Select the ‘Maven Web App’ Archetype from the list of options and click next.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>JavaServletRequestDispatcher</groupId> <artifactId>JavaServletRequestDispatcher</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> </project>
We can start adding the dependencies that developers want like Servlets, Junit etc. Let’s start building the application!
3. Application Building
Below are the steps involved in developing this application.
3.1 Maven Dependencies
Here, we specify the dependencies for the Servlet API. The rest dependencies will be automatically resolved by the Maven framework and the updated file will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>JavaServletRequestDispatcher</groupId> <artifactId>JavaServletRequestDispatcher</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>JavaServletRequestDispatcher Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> </build> </project>
3.2 Java Class Creation
Let’s create the required Java files. Right-click on src/main/java
folder, New -> Package
.
A new pop window will open where we will enter the package name as: com.jcg.servlet
.
Once the package is created in the application, we will need to create the controller classes. Right-click on the newly created package: New -> Class
.
A new pop window will open and enter the file name as: Login
. The Login Servlet Controller class will be created inside the package: com.jcg.servlet
.
Repeat the step (i.e. Fig. 12) and enter the filename as: Welcome
. The Welcome Servlet Controller class will be created inside the package: com.jcg.servlet
.
3.2.1 Implementation of Login Servlet Controller Class
In this example, we are validating the login credentials entered by the user. If the login credentials are correct, the business logic will forward the request to the Welcome
Servlet, otherwise, the business logic will include the response in the current servlet and shows an error message.
Let’s see the simple code snippet that follows this implementation.
Login.java
package com.jcg.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/loginServlet") public class Login extends HttpServlet { private static final long serialVersionUID = 1L; // This Method Is Called By The Servlet Container To Process A 'POST' Request. public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { handleRequest(req, resp); } public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { resp.setContentType("text/html"); // Post Parameters From The Request String param1 = req.getParameter("username"); String param2 = req.getParameter("password"); // Print The Response PrintWriter out = resp.getWriter(); out.write("<html><body><div id='serlvetResponse' style='text-align: center;'>"); // Creating The 'RequestDispatcher' Object For Forwading The HTTP Request RequestDispatcher rdObj = null; // Checking For Null & Empty Values if(param1 == null || param2 == null || "".equals(param1) || "".equals(param2)) { out.write("<p id='errMsg' style='color: red; font-size: larger;'>Please Enter Both Username & Password... !</p>"); rdObj = req.getRequestDispatcher("/index.jsp"); rdObj.include(req, resp); } else { System.out.println("Username?= " + param1 + ", Password?= " + param2); // Authentication Logic & Building The Html Response Code if((param1.equalsIgnoreCase("jcg")) && (param2.equals("admin@123"))) { rdObj = req.getRequestDispatcher("/welcomeServlet"); rdObj.forward(req, resp); } else { out.write("<p id='errMsg' style='color: red; font-size: larger;'>You are not an authorised user! Please check with administrator!</p>"); rdObj = req.getRequestDispatcher("/index.jsp"); rdObj.include(req, resp); } } out.write("</div></body></html>"); out.close(); } }
3.2.2 Implementation of Welcome Servlet Controller Class
This Servlet class will display the welcome message. Let’s see the simple code snippet that follows this implementation.
Welcome.java
package com.jcg.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/welcomeServlet") public class Welcome extends HttpServlet { private static final long serialVersionUID = 1L; // This Method Is Called By The Servlet Container To Process A 'POST' Request. public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { handleRequest(req, resp); } public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { resp.setContentType("text/html"); // Post Parameters From The Request String param1 = req.getParameter("username"); // Building & Printing The HTML Response Code PrintWriter out = resp.getWriter(); out.write("<html><body><div id='serlvetResponse' style='text-align: center;'>"); out.write("<h2>Servlet Request Dispatcher Example</h2>"); out.write("<p style='color: green; font-size: large;'>Congratulations! <span style='text-transform: capitalize;'>" + param1 + "</span>, You are an authorised login!</p>"); out.write("</div></body></html>"); out.close(); } }
3.3 Creating JSP Views
Servlet supports many types of views for different presentation technologies. These include – JSP
, HTML
, XML
etc. So let us write a simple view in JavaServletRequestDispatcher/src/main/webapp/
. To make the form works with Java servlet, we need to specify the following attributes for the <form>
tag:
method="post"
: To send the form data as an HTTP POST request to the server. Generally, form submission should be done in HTTP POST methodaction="Servlet Url"
: Specifies the relative URL of the servlet which is responsible for handling the data posted from this form
Add the following code to it:
index.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Servlet Login</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="js/jquery-1.8.0.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#userInput, #passInput').click(function() { $("#errMsg").hide(); }); }); </script> <style type="text/css"> .paddingBtm { padding-bottom: 12px; } </style> </head> <body> <center> <h2>Servlet Request Dispatcher Example</h2> <form id="loginFormId" name="loginForm" method="post" action="loginServlet"> <div id="usernameDiv" class="paddingBtm"> <span id="user">Username: </span><input id="userInput" type="text" name="username" /> </div> <div id="passwordDiv" class="paddingBtm"> <span id="pass">Password: </span><input id="passInput" type="password" name="password" /> </div> <div id="loginBtn"> <input id="btn" type="submit" value="Login" /> </div> </form> </center> </body> </html>
4. Run the Application
As we are ready with all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server
.
Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser.
5. Project Demo
Open your favorite browser and hit the following URL. The output page will be displayed.
http://localhost:8085/JavaServletRequestDispatcher/
Server name (localhost) and port (8085) may vary as per your tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!
Try to enter wrong credentials and the Servlet business logic will display the invalid credentials message.
Now enter the correct credentials as per the configuration (i.e. User: jcg and Password: admin@123) and the Servlet business logic will redirect you to the application’s welcome page.
That’s all for this post. Happy Learning!!
6. Conclusion
In this section, developers learned how to retrieve the HTTP POST request parameters in a Servlet. Developers can download the sample application as an Eclipse project in the Downloads section. I hope this article served you with whatever developers were looking for.
7. Download the Eclipse Project
This was an example of Servlet Application Login.
You can download the full source code of this example here: JavaServletRequestDispatcher