Categories: Servlet

RequestDispatcher Interface

In this tutorial you will learn how to use forward() method of RequestDispatcher in Servlet
forward() method of RequestDispatcher forwards the request made by the client by the the resource (any of them servlet , jsp, html, etc.) on the server without including the content of the requested resource.syntax :
void forward(request, response) throws ServletException, IOException

RequestDispacher

The RequestDispacher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp.This interface can also be used to include the content of another resource also. It is one of the way of servlet collaboration.

There are two methods defined in the RequestDispatcher interface.

Methods of RequestDispatcher interface

The RequestDispatcher interface provides two methods. They are:

  1. public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.

    HttpSession interface

    As you see in the above figure, response of second servlet is sent to the client. Response of the first servlet is not displayed to the user.

  2. public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML file) in the response.

    As you can see in the above figure, response of second servlet is included in the response of the first servlet that is being sent to the client.

Getting the object of RequestDispatcher

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

Syntax of getRequestDispatcher method:

public RequestDispatcher getRequestDispatcher(String resource);  

Example of using getRequestDispatcher method

RequestDispatcher rd=request.getRequestDispatcher("/welcomeServlet");  
  //welcomeServlet is the url-pattern of the second servlet  
  rd.forward(request, response);//method may be include or forward  

Example of RequestDispatcher interface

In this example, we are validating the password entered by the user. If password is servlet, it will forward the request to the WelcomeServlet, otherwise will show an error message: sorry username or password error!. In this program, we are checking for hard coded information. But you can check it to the database also that we will see in the development chapter.

1. :login.html file for getting input from the user.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Page</title>
</head>
<body>
<form method="get" action="loginServlet">
<p>Enter your info in the following text boxes</p>
Enter your name <input type="text" name="text1"/><br>
Enter your password <input type="password" name="text2"/><br>
<input type="submit" value="submit"/>
</form>
</body>
</html>

2. LoginServlet.java file: a servlet class for processing the response. If password is servlet, it will forward the request to the welcome servlet.

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
  
public class LoginSevlet extends HttpServlet {  
  
public void doPost(HttpServletRequest request, HttpServletResponse response)  
        throws ServletException, IOException {  
  
    response.setContentType("text/html");  
    PrintWriter out = response.getWriter();  
          
    String userName=request.getParameter("userName");  
    String userPass=request.getParameter("userPass");  
          
    if(userPass.equals("sweety")){  
        RequestDispatcher rd=request.getRequestDispatcher("welcomeServlet");  
        rd.forward(request, response);  
    }  
    else{  
        out.print("Sorry User Name or Password Error!");  
        RequestDispatcher rd=request.getRequestDispatcher("/login.html");  
        rd.include(request, response);  
                      
        }  
    }  
  
}  

3. WelcomeServlet.java file: a servlet class for displaying the welcome message.

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

4. web.xml file: a deployment descriptor file that contains the information about the servlet.

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>servletRequestDispatcher</display-name>
<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>  
  
  <welcome-file-list>  
   <welcome-file>login.html</welcome-file>  
  </welcome-file-list>  

</web-app>

Now let us start tomcat server using C:Program Files (x86)Apache Software FoundationTomcat 7.0binstartup.bat (on windows) or /bin/startup.sh (on Linux/Solaris etc.) and finally type http://localhost:8080/login.html in browser’s address box. If everything goes fine, you would get following result:

With wrong password it request dispatched to again login form.

With right user name and password.

<<Previous <<   || Index ||   >>Next >>

 

 

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago