< Prev
Next >

Request Dispatching

In this article, we are going to understand how to dispatch a request from one servlet to another servlet by using the RequestDispatcher object. This helps when the request processing or the response generation has to be shared between multiple servlets.

An application could be served by many servlets which are configured in a deployment descriptor file, web.xml. Using this configuration file with the RequestDispatcher object we can -
RequestDispatcher is an interface and it is a part of the Servlet API. The full path to import and access the methods of RequestDispatcher is javax.servlet.RequestDispatcher.

How to create an object of RequestDispatcher

RequestDispatcher methods

Let's take a look at the methods part of javax.servlet.RequestDispatcher interface.

Methods Description

void forward(ServletRequest request, ServletResponse response)

This method forwards the request to another Servlet, JSP or a static HTML page.

void include(ServletRequest request, ServletResponse response)

This method includes the contents of another Servlet, JSP or static HTML page in the response.

Creating a webpage which calls the Servlet

We are creating a webpage which asks the user to click a button named Yes, let's do it!, which when clicked dispatches or forwards the current request from the servlet named FirstServlet in the deployment descriptor file(web.xml).


<title> ServletRequest Demo </title>

<b>Do you want to forward the request from  first servlet to the second servlet?</b>

<form action = "FirstServlet">
<input type = "submit" value = "Yes, let's do it!" />



Using RequestDispatcher to forward a request

In the upcoming example, we are creating a servlet by extending the GenericServlet abstract class. GenericServlet class implements the Servlet and ServletConfig interfaces, hence we can directly call the methods of ServletConfig within this servlet.

Please Subscribe

Please subscribe to our social media channels for daily updates.

Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page



Please check our latest addition