< Prev
Next >



Request Dispatching



In this article, we are going to understand how to dispatch the request from one Servlet to another Servlet using the RequestDispatcher object. This helps when the request processing or the response generation has to be shared between the 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 all the methods provided by ServletContext 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).

Webpage1.jsp
<html>

<head>
<title> ServletRequest Demo </title>
</head>


<body>
<b>Do you want to forward the request from  first Servlet to the second Servlet?</b>
<br/>
<br/>
<br/>

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

</body>
</html>





Using RequestDispatcher to forward a request


We are creating a Servlet extending GenericServlet abstract class. GenericServlet class implements Servlet and ServletConfig interface, hence we can directly call the methods of ServletConfig within this Servlet.

Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
C++ and Python

Ad2