What is a request dispatcher and how do i use it?
Author: Deron Eriksson
Description: This tutorial describes how to use a request dispatcher in a servlet.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0) || Tomcat 5.5.20


Page:    1 2 >

A RequestDispatcher is an extremely important JavaSW class that allows for 'including' content in a request/response or 'forwarding' a request/response to a resource. As a typical example, a servletW can use a RequestDispatcher to include or forward a request/response to a JSPW. In Model-View-Controller programming in Java, a servlet typically serves as the 'controller'. The controller basically contains or references code to perform particular actions, and it decides which 'view' to send the user to. In Java, the view is typically a JSP. Thus, a RequestDispatcher performs a very important role in Java MVCW architecture since it can serve as the mechanism for the 'controller' (servlet) to pass the user to the 'view' (JSP).

The TestServlet class demonstrates RequestDispatcher including and forwarding.

TestServlet.java

package com.cakes;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		performTask(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		performTask(request, response);
	}

	private void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("TestServlet says hi<br/>");

		String action = request.getParameter("action");
		if (action != null) {
			RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
			if ("include".equalsIgnoreCase(action)) {
				rd.include(request, response);
			} else if ("forward".equalsIgnoreCase(action)) {
				rd.forward(request, response);
			}
		}

	}

}

The TestServlet RequestDispatcher object references the index.jsp file, shown below:

index.jsp

index.jsp says hi

The test project contains the TestServlet and index.jsp file in the project structure shown here:

'test' project

(Continued on page 2)

Page:    1 2 >