RequestDispatcher Interface:-



javax.servlet.RequestDispatcher interface is used to receive a client request and can do one of the following two things -
1- It can forward client request to some other servlet, jsp or html file.
2- It can include some other file (servlet, jsp or html) into currently executing file (servlet or jsp, which contain the RequestDispatcher).
It has the following two methods -
1- public void forward(ServletRequest request, ServletResponse response)throws ServletException,IOException - This method is used to forward client request to some other servlet, jsp or html file specified by RequestDispatcher.
2- public void include(ServletRequest request, ServletResponse response)throws ServletException,IOException - This method is used to include some other file (servlet, jsp or html) specified by RequestDispatcher into currently executing file (servlet or jsp, which contain the RequestDispatcher).

Creating Object of RequestDispatcher -

We can get a reference to RequestDispatcher by using ServletRequest's method "getRequestDispatcher()".It has the following syntax -
 public RequestDispatcher getRequestDispatcher (String resourceURL)
 
For example -
RequestDispatcher rdp = request.getRequestDispatcher("Home.jsp");   
Now according to our requirement we can use either forward() or include() method.
Using forward() method -
rdp.forward(request, response);  // It will forward the user request from current servlet to the Home.jsp file.
Using include() method -
rdp.include(request, response);  // It will include Home.jsp file into the currently executing servlet. 

forward() method works as shown below -


Fig: RequestDispatcher forward() method


include() method works as shown below -


Fig: RequestDispatcher include() method


Relative URL -

Instead of specifying full url, we can also specify relative resourceURL in getRequestDispatcher().
For example - suppose client make the following request - "http://www.gettechnotes.com/MyProject/servs/servlet1".
And servlet1 uses a RequestDispatcher to forward client request to servlet2 contained in package "test". RequestDispatcher can use the relative url to forward request to servlet2. And it can use it in one of the following two ways -
1- With /(forward slash) -
RequestDispatcher rdp = request.getRequestDispatcher("/test/servlet2");
In this case server will use the complete url relative to your project web-app. So the url used by server will be - "http://www.gettechnotes.com/MyProject/test/servlet2".

2- Without /(forward slash) -
RequestDispatcher rdp = request.getRequestDispatcher("test/servlet2");
In this case server will use the complete url relative to your current request url. So the url used by server will be - "http://www.gettechnotes.com/MyProject/servs/test/servlet2".

Example -

In this example, default page (index.html) will ask for username and password, if we enter correct username and password, it will forward us to Home page, otherwise it will again show you index.html page with an error message.
1- index.html or index.jsp - This will be default page.
<html>
    <head>
        <title>Login Form</title>
    </head>
    <body>
     <form method="post" action="LoginCheck">
     <table border="1px">
      <tr>
        <td>User Name: </td>
        <td><input type="text" name="t1"></td>
      </tr>
      <tr>
        <td>Password </td>
        <td><input type="password" name="t1"></td>
      </tr>
      <tr>
        <td><input type="submit" value="Login"></td>
        <td><input type="reset" value="Reset"></td>
      </tr>
                
    </table>
    </form>
    </body>
</html>
  
This will create a login form with two fields Username and Password, When we click the Login button it will redirect us to LoginChek servlet.
2- LoginCheck servlet - Create a Package named "servs" and within "servs", create a Servlet named "LoginCheck".
LoginCheck servlet will get the username and password entered by user, and if user enters the valid username and password (username = admin and password = 123 in our example) then redirected to Home servlet, otherwise it include index.html in LoginCheck servlet.
package servs;

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


public class LoginCheck extends HttpServlet {


    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try
        {
            PrintWriter out = response.getWriter();
            String nm = request.getParameter("t1");
            String ps = request.getParameter("t2");
            if(nm.equals("admin") && ps.equals("123"))
            {
                RequestDispatcher rdp = request.getRequestDispatcher("Home");
                rdp.forward(request, response);
            }       
            else
            {
                out.println("<p style='color:red'>Wrong username or password</p>");
                RequestDispatcher rdp = request.getRequestDispatcher("index.html");
                rdp.include(request, response);
            }
        }
       catch(Exception ex)
       {
           System.out.println(ex);
       }
    }
}

3- Home servlet within servs create servlet named "Home".
package servs;

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

public class Home extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
    {
        try
        {
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Home</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Weclome to Home</h1>");
            out.println("</body>");
            out.println("</html>");
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}    

4- web.xml - Add the follwing code to web.xml within web-app
<servlet>
  <servlet-name>LoginCheck</servlet-name>
  <servlet-class>servs.LoginCheck</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>LoginCheck</servlet-name>
  <url-pattern>/LoginCheck</url-pattern>
</servlet-mapping>
<servlet>
  <servlet-name>Home</servlet-name>
  <servlet-class>servs.Home</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>Home</servlet-name>
  <url-pattern>/Home</url-pattern>
</servlet-mapping>    

5- Now run your project, and it will show you index.html page, enter username and password and click Login button.



When we enter correct user name and password, it will display following output -



If we enter incorrect username or password it will display the following output -