Servlet RequestDispatcher

In this tutorial you will learn about the Servlet RequestDispatcher and its application with practical example.

Servlet RequestDispatcher Interface

This interface defines an object that receives request from the client and sends them to any resource which can be Servlet,HTML or JSP. This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resources.

RequestDispatcher Interface Methods

There are two methods which are provided by the RequestDispatcher interface.

public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException :- This method is used to forwards a request from a servlet to another resource such as servlet, JSP, or HTML file.
public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:- This method is used to includes the content of a resources (like servlet, JSP or HTML file) in the response.

RequestDispatcher Method

Syntax:-

The getRequestDisptacher() method is used to returns the object of RequestDisptacher and the syntax is shown below.

Example:-

Let’s understand this interface by an example. The files which are needed for this example are :

index.html:- From this page we are going to send request to servlet.
Login.java (Servlet) :- This is servlet class , which will process the response. If username And Password are matched then it will forward the request to Home.java servlet.
Home.java(Servlet):- This servlet will display the Welcome message to user.
web.xml file:- This is a deployment descriptor file which is used to contain information about the servlet, welcome file etc.

Check below code for creating this file.

index.html :-

login.java :-

You can check that we have send request using post method from index.hmtl file. SO here it is necessary to get data in doPost() method of servlet. We will make condition for checking user name and password here, if it is correct so using getRequestDispatcher() method we will send request to Next Servlet which is Home in our case.

Syntax:-

You can also check it in below code.

Recommended:-  Servlet URL Rewriting

Home.java :-

if the username and password is correct so we will get this servlet file. Check below code for this.

Recommended:-  Servlet SendRedirect

web.xml :-

check below xml file , you will find welcome file, servlet deployment etc.

Recommended:-  Servlet HttpSession

Output:-

Now let’s check the output of this sample project. Check All the images of this code. You can also try this.
1. This will be the case in which you entered wrong username and password.

image001

2. After entering correct username and password the output will be like below image.

image002

In this tutorial we have learn about the Servlet RequestDispatcher and its application with practical example. I hope you will like this tutorial.