Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
354
Chapter 15 Integrating Servlets and JSP
partially process the data, set up beans, then forward the results to one of a
number of different JSP pages, depending on the circumstances. In early JSP
specifications, this approach was known as the model 2 approach to JSP.
Rather than completely forwarding the request, the servlet can generate part
of the output itself, then include the output of one or more JSP pages to
obtain the final result.
15.1 Forwarding Requests
The key to letting servlets forward requests or include external content is to
use a
RequestDispatcher
. You obtain a
RequestDispatcher
by calling the
getRequestDispatcher
method of
ServletContext
, supplying a URL rel
ative to the server root. For example, to obtain a
RequestDispatcher
associ
ated with
http://yourhost/presentations/presentation1.jsp
, you
would do the following:
String url = "/presentations/presentation1.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
Once you have a
RequestDispatcher
, you use
forward
to completely
transfer control to the associated URL and use
include
to output the associ
ated URL's content. In both cases, you supply the
HttpServletRequest
and
HttpServletResponse
as arguments. Both methods throw
Servlet
Exception
and
IOException
. For example, Listing 15.1 shows a portion of a
servlet that forwards the request to one of three different JSP pages, depend
ing on the value of the
operation
parameter. To avoid repeating the
getRe
questDispatcher
call, I use a utility method called
gotoPage
that takes the
URL, the
HttpServletRequest
and the
HttpServletResponse
; gets a
RequestDispatcher
; and then calls
forward
on it.
Using Static Resources
In most cases, you forward requests to a JSP page or another servlet. In some
cases, however, you might want to send the request to a static HTML page.
In an e commerce site, for example, requests that indicate that the user does
not have a valid account name might be forwarded to an account application
page that uses HTML forms to gather the requisite information. With
GET
requests, forwarding requests to a static HTML page is perfectly legal and
requires no special syntax; just supply the address of the HTML page as the
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved