Signup/Sign In

Request Dispatcher in Servlet

In Java, the RequestDispatcher Interface is used for dispatching the request to a resource i.e Html, servlet or JSP. The Contents of another resource can be included in this interface. There are two methods of RequestDispatcher. They are as following:


Servlet: Methods of RequestDispatcher

RequestDispatcher interface provides two important methods

MethodsDescription
public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOExceptionIt is used for forwarding the request from one servlet to another servlet on a server.
public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException It is used for including the content of the resource in the response.

forward() method:

forward-method-dispatcher

include() method:

include-method-dispatcher

Example of forward() and include() method on Eclipse

For creating a program using forward() and include() method below is the directory structure of the program:

forward-include

Following are the steps for creating the program.

Step 1: Create a dynamic project on eclipse by clicking on File => New => Dynamic Web Project

file-dispatcher

Step 2: Now create an HTML file.

Right-click on the project and then click on HTML file. Give the name of the file and then click on the finish button.

file-dispatcher

And write the below code.

Index.html

    
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>studytonight</title>
</head>
<body>
<form align="center" action="display" method="post"> 
<h3>studytonight.com</h3>
<hr>
Name: <input type="text" name="val1"><br> <br>
User Id: <input type="text" name="val2"><br> <br>
Password: <input type="password" name="val3"><br> <br> 
<input type="submit" value="login">  
</form>  
</body>
</html>
    

Step 3: Now add the below code in web.xml file.

web.xml file is a deployment descripter. Here we have all the configurations.

    
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>forward</display-name>
  <servlet>  
    <servlet-name>demo5</servlet-name>  
    <servlet-class>forward.demo5</servlet-class>  
  </servlet>  
  <servlet>  
    <servlet-name>demo5i</servlet-name>  
    <servlet-class>forward.demo5i</servlet-class>  
  </servlet>  
  
  
  <servlet-mapping>  
    <servlet-name>demo5</servlet-name>  
    <url-pattern>/display</url-pattern>  
  </servlet-mapping>  
  <servlet-mapping>  
    <servlet-name>demo5i</servlet-name>  
    <url-pattern>/display1</url-pattern>  
  </servlet-mapping>  
  
  <welcome-file-list>  
   <welcome-file>index.html</welcome-file>  
  </welcome-file-list>  
</web-app>
    

Step 4: Now next create a servlet. For this create a class. Give the package name and the class name.

For this example we need two servlet classes.

servlet-classes
servelet_class

Now add the below code in the class file.

demo5.java

    
package forward;

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
public class demo5 extends HttpServlet {  
  
public void doPost(HttpServletRequest request, HttpServletResponse response)  
        throws ServletException, IOException {  
  
    response.setContentType("text/html");  
    PrintWriter out = response.getWriter();  
          
    String n=request.getParameter("val1");  
    String u=request.getParameter("val2"); 
    String p=request.getParameter("val3");  
          
    if(p.equals("studytonight"))
            {  
        RequestDispatcher rd=request.getRequestDispatcher("display1");  
        rd.forward(request, response);  
    }  
    else{  
        out.print("Incorrect UserId or Password");  
        RequestDispatcher rd=request.getRequestDispatcher("/index.html");  
        rd.include(request, response);  
                      
        }  
    }  
  
}  
    

demo5i.java

    
package forward;

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
public class demo5i extends HttpServlet {  
  
    public void doPost(HttpServletRequest request, HttpServletResponse response)  
        throws ServletException, IOException {  
  
    response.setContentType("text/html");  
    PrintWriter out = response.getWriter();  
          
    String n=request.getParameter("val2");  
    out.print("Welcome "+n);  
    }  
  
} 
    

Now, Run the code.

To run the code, right-click on the project and select Run As => Run on Server.

dispatcher-output

Below is the index.html page. Fill all the fields and click on the login button for landing in the
servlet page.

dispatcher-output

If your password is correct then it will land on the servlet page demo5.java

dispatcher-output

If your password is incorrect then it will land on demo5i.java page.

dispatcher-output



How to get an Object of RequestDispatcher

getRequestDispatcher() method of ServletRequest returns the object of RequestDispatcher.

RequestDispatcher rs = request.getRequestDispatcher("hello.html");
rs.forward(request,response);

RequestDispatcher detail and instantiation using forward

OR

RequestDispatcher rs = request.getRequestDispatcher("hello.html");
rs.include(request,response);

RequestDispatcher detail and instantiation using include


Example demonstrating usage of RequestDispatcher

In this example, we will show you how RequestDispatcher is used to forward or include response of a resource in a Servlet. Here we are using index.html to get username and password from the user, Validate Servlet will validate the password entered by the user, if the user has entered "studytonight" as password, then he will be forwarded to Welcome Servlet else the user will stay on the index.html page and an error message will be displayed.

Files to be created :

  • index.html will have form fields to get user information.
  • Validate.java will validate the data entered by the user.
  • Welcome.java will be the welcome page.
  • web.xml , the deployment descriptor.

index.html

<form method="post" action="Validate">
Name:<input type="text" name="user" /><br/>
Password:<input type="password" name="pass" ><br/>
<input type="submit" value="submit">
</form>

Validate.java

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

public class Validate extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String name = request.getParameter("user");
            String password = request.getParameter("pass");

            if(password.equals("studytonight"))
            {
                RequestDispatcher rd = request.getRequestDispatcher("Welcome");
                rd.forward(request, response);
            }
            else
            {
                out.println("<font color='red'><b>You have entered incorrect password</b></font>");
                RequestDispatcher rd = request.getRequestDispatcher("index.html");
                rd.include(request, response);
            }
        }
        finally {            
            out.close();
        }
        
    }
}

Welcome.java

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

public class Welcome extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            out.println("<h2>Welcome user</h2>");
        } 
        finally {            
            out.close();
        }
    }
}

web.xml

<web-app>
    <servlet>
        <servlet-name>Validate</servlet-name>
        <servlet-class>Validate</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Welcome</servlet-name>
        <servlet-class>Welcome</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Validate</servlet-name>
        <url-pattern>/Validate</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Welcome</servlet-name>
        <url-pattern>/Welcome</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        </welcome-file-list>
</web-app>

This will be the first screen. You can enter your Username and Password here.

request dispatcher example


When you click on Submit, Password will be validated, if it is not 'studytonight' , error message will be displayed.

request dispatcher example


Enter any Username, but enter 'studytonight' as password.

request dispatcher example


Password will be successfully validated and you will be directed to the Welcome Servlet.

request dispatcher example