Advertisement



< 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).

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>



Advertisement




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




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement