Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
15.1 Forwarding Requests
357
The Servlet 2.2 specification adds a third way to send data to the destina
tion page when using
GET
requests: simply append the query data to the
URL. For example,
String address = "/path/resource.jsp?newParam=value";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(address);
dispatcher.forward(request, response);
This technique results in an additional request parameter of
newParam
(with a value of
value
) being added to whatever request parameters already
existed. The new parameter is added to the beginning of the query data so
that it will replace existing values if the destination page uses
getParameter
(use the first occurrence of the named parameter) rather than
get
ParameterValues
(use all occurrences of the named parameter).
Interpreting Relative URLs in the Destination
Page
Although a servlet can forward the request to arbitrary locations on the same
server, the process is quite different from that of using the
sendRedirect
method of
HttpServletResponse
(see Section 6.1). First,
sendRedirect
requires the client to reconnect to the new resource, whereas the
forward
method of
RequestDispatcher
is handled completely on the server. Sec
ond,
sendRedirect
does not automatically preserve all of the request data;
forward
does. Third,
sendRedirect
results in a different final URL,
whereas with
forward,
the URL of the original servlet is maintained.
This final point means that, if the destination page uses relative URLs for
images or style sheets, it needs to make them relative to the server root, not
to the destination page's actual location. For example, consider the following
style sheet entry:
HREF="my styles.css"
TYPE="text/css">
If the JSP page containing this entry is accessed by means of a forwarded
request,
my styles.css
will be interpreted relative to the URL of the origi
nating servlet, not relative to the JSP page itself, almost certainly resulting in
an error. The solution is to give the full server path to the style sheet file, as
follows:
HREF="/path/my styles.css"
TYPE="text/css">
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