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

(Continued from page 1)

If the TestServlet (which is mapped to 'test') is hit with no parameters, we see the following:

test servlet hit via web browser

If "action=include" is appended as a URL parameter, we see that the RequestDispatcher object 'includes' the contents of index.jsp in the result sent back to the browser. As you can see, the request dispatcher results are appended to the previous output results generated by TestServlet.

RequestDispatcher 'includes' content

If "action=forward" is appended as a URL parameter, the RequestDispatcher object 'forwards' the request/response to index.jsp. Unlike the case with the 'include', the 'forward' discards the previous output that TestServlet had written to the response. As a result, we only see the output generated by index.jsp.

RequestDispatcher 'forwards' request

The RequestDispatcher include()/forward() methods are used extensively in servlet/JSP programming, so it's good to have a solid understanding of them.

Page: < 1 2