In this tutorial, you will learn how to transfer control to Another Web Component using RequestDispatcher in java servlet.
In this tutorial, you will learn how to transfer control to Another Web Component using RequestDispatcher in java servlet.In this tutorial, you will learn how to transfer control to Another Web Component using RequestDispatcher in java servlet.
RequestDispatcher :
RequestDispatcher interface is defined in javax.servlet package. RequestDispatcher object contains request of client and transfer control to another web component. The servlet container is responsible for creating object of RequestDispatcher which is used as a wrapper around a server resource located at a particular path or given by a particular name. For transferring control to the another component you can invoke the forward method of a RequestDispatcher.
Methods : Following are methods -
Example : In this example we are using RequestDispatcher and its forward() method to transfer control to the home.html.
RequestDispatcherExamplejava
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RequestDispatcherExample extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); ServletContext context=getServletContext(); RequestDispatcher requestDispatcher=context.getRequestDispatcher("/home.html"); requestDispatcher.forward(request, response); } }
home.html -
<html> <head> <title>Home Page</title> </head> <body> <h2 align="center">Welcome</h2> <h3>This is your home page.</h3> </body> </html>
web.xml -
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>RequestDispatcher</display-name> <servlet> <description></description> <display-name>RequestDispatcherExample</display-name> <servlet-name>RequestDispatcherExample</servlet-name> <servlet-class>RequestDispatcherExample</servlet-class> </servlet> <servlet-mapping> <servlet-name>RequestDispatcherExample</servlet-name> <url-pattern>/RequestDispatcherExample</url-pattern> </servlet-mapping> </web-app>
Output :