Advertisement



< Prev
Next >



forward() method of RequestDispatcher



In this article, we are going to understand how to forward the contents of one Servlet to another Servlet using the forward() method of RequestDispatcher object. 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 with the forward() method we can forward the contents of one Servlet to another Servlet.

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







Syntax of forward() method of RequestDispatcher


Method Description
void forward(ServletRequest request, ServletResponse response) This method forwards the request to another Servlet, JSP or a static HTML page.





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 include the request from  another Servlet to the current 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

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

PYTHON


Advertisement