Request Dispatcher Interface in Java

Introduction

This article explains the Request Dispatcher interface in Java. The NetBeans IDE is used for the sample example.

What is RequestDispatcher

It is an interface of the Servlet API, the implementation of it is provided by server vendors. This interface provides the facility of dispatching the request to another resource; it may be HTML, servlet or JSP. It is also used to include the content of another resource also. This interface provides the following methods.

1. include()

Used to include the contents of a HTML page or response of a servlet to the response of the current servlet.

Syntax

public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException

2. forward()

Used to forward a request to another servlet or HTML page.

Syntax

public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException

An object of type request of dispatches is obtained using the following method.

1. getRequestDispatcher()

Returns the object of RequestDispatcher.

Syntax

public RequestDispatcher getRequestDispatcher(String url of resource) throws ServletException

In a web app a request can be proceed in the following ways.

1. Processing by a single servlet.

Fig-1.jpg

2. Collaborative processing with indiums.

Fig-2.jpg

3. Collaborative processing with forwarding.

Fig-3.jpg

Example

Let's see an example.

In this example we create a login page in which we provide a validation of name and password.

We need to create the following files.

1. index.html

Obtains the information (as name and password) from users.

2. LoginServlet.java

Creates the following tasks:

  • check validation
  • Used RequestDispatcher to forward information to various pages.

3. WelcomeServlet.java

Displays user login information that "he is successfully login".

4. web.xml

This XML page maps servlets to a web server.

The following is the procedure we need to follow.

Step 1

Opens the Netbeans IDE.

Fig-4.jpg

Step 2

Open the project menu then select "New Project" then a new window opens; select "Java" -> "Java web" as shown below.

Fig-5.jpg

Step 3

After clicking on Next, enter your project name as "RequestDispatcherDemo" and click on "Next".

Fig-6.jpg

Step 4

Now select your server and Java version and click on "Finish", as shown below.

Fig-7.jpg

Step 5

Now delete the default file index.jsp from your project menu and create a new HTML file as in the following:

Right-click on "Web pages" then select "New" -> "HTML file", as shown below.

Fig-8.jpg

Step 6

Type file name as "index" and click on "Finish", as shown below.

Fig-9.jpg

Step 7

Now provide the following code for it.

<!DOCTYPE html>

<html>   

    <body>

        <form method="post" action="LoginServlet">

            User Name:<input type="text" name="uname"><br>

            Password:<input type="password" name="password"><br>

            <input type="submit" value="login">

        </form>

    </body>

</html>

Fig-10.jpg

Step 8

Now create a new servlet file as in the following:

Right-click on the project then select "New" -> "Servlet" as shown below.

Fig-11.jpg

Step 9

Type your servlet name as "LoginServlet" and click on "Next" as shown below.

Fig-12.jpg

Choose combo-box to add this servlet information to the XML file, then click on "Finish".

Fig-13.jpg

Step 10

Provide the following code for it:

LoginServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        String name = request.getParameter("uname");

        String pass = request.getParameter("password");

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        if (pass.equals("sandeep")) {

            RequestDispatcher rd = request.getRequestDispatcher("WelcomeServlet");

            rd.forward(request, response);

        } else {

            out.println("Sorry you entered wrong Parrword, Please try again with correct password...");

            RequestDispatcher rd = request.getRequestDispatcher("/index.html");

            rd.include(request, response);

        }

    }

}

Fig-14.jpg

Step 11

Now create another servlet with the name "WelcomeServlet" and provide the following code for it:

WelcomeServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class WelcomeServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        String name = request.getParameter("uname");

        out.println("Welcome " + name + " You are successfully login");

    }

}

Fig-15.jpg

Step 12

Now if you have attached both your servlet pages with the XML file then you don't need to create a web.xml file, since it is created in the Netbeans IDE by default. Check the contents of this file to ensure it is the same as below.

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <servlet>

        <servlet-name>LoginServlet</servlet-name>

        <servlet-class>LoginServlet</servlet-class>

    </servlet>

    <servlet>

        <servlet-name>WelcomeServlet</servlet-name>

        <servlet-class>WelcomeServlet</servlet-class>

    </servlet>

    <servlet-mapping>

        <servlet-name>LoginServlet</servlet-name>

        <url-pattern>/LoginServlet</url-pattern>

    </servlet-mapping>

    <servlet-mapping>

        <servlet-name>WelcomeServlet</servlet-name>

        <url-pattern>/WelcomeServlet</url-pattern>

    </servlet-mapping>

    <session-config>

        <session-timeout>

            30

        </session-timeout>

    </session-config>

</web-app>

Step 13

Now run your project; a window will open as in the following:

Fig-16.jpg

Note: The password we provide in LoginServlet is "sandeep".

Now check the login using the following.

1. Wrong password

Fig-17.jpg

Fig-18.jpg

2. Correct Password as "sandeep".

Fig-19.jpg

Fig-20.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all