Share on Google+Share on Google+

Java Servlet :RequestDispatcher Interface

In this tutorial, you will learn how to transfer control to Another Web Component using RequestDispatcher in java servlet.

Java Servlet :RequestDispatcher Interface

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 -

  • forward(ServletRequest request, ServletResponse response) : This method forwards a request from a servlet to another web component(servlet/JSP file/HTML file) on the server.
  • include(ServletRequest request, ServletResponse response) : This method includes the content of a resource in the response.

Example : In this example we are using  RequestDispatcher and its forward() method to transfer control to the home.html.



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 {
		PrintWriter out=response.getWriter();
		ServletContext context=getServletContext();
		RequestDispatcher requestDispatcher=context.getRequestDispatcher("/home.html");
		requestDispatcher.forward(request, response);

home.html -


<title>Home Page</title>
<h2 align="center">Welcome</h2>
<h3>This is your home page.</h3>

web.xml -

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="2.5">


Output :



Posted on: October 6, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null