Java Reference
In-Depth Information
the loop, one for each iteration of the loop. (If you're not picturing that, be
patient. There are examples of this coming up. If you're not conversant in
HTML, then you better check out some of the HTML references at the end
of this chapter. We're going to assume that you speak HTML fluently. Come
on—we can't cover everything in one book.)
The other side of dynamic content comes from variable input. Google's
search engine, for example, generates different pages for different search strings.
It is the variation in user input that results in varying output pages. On a Web
page, user input typically comes from an HTML form. The form values can
be passed either as parameters on the URL or as
POST
values. URL parameters
are also easy to generate by hand, or to code in place in
<a>
tags. For example,
<a href="/servlet/doSuch?cmd=find&value=joe">
is an HTML tag for a hyperlink which will invoke the
doSuch
servlet and pass
in the parameters
cmd
and
value
. (It's a servlet not because the pathname is
/servlet
, but we use that for illustrative purposes. In fact, the servlet invoked
may not even be called
doSuch
; it all part of servlet mapping that recognizes
certain URLs as aliases for particular servlets. See Chapter 19 for a fuller
explanation.)
The point is, we can invoke the same servlet repeatedly (even simultane-
ously) but with different values for our parameters, so we can program it for
different behaviors and different output.
These parameters are available to the servlet via the
request
argument of
the
doGet()
and
doPost()
methods. You can get an enumerator over all of
the arguments (using
getParameterNames()
), or if you know it's name (and
you likely would, since you're writing the program) you can ask for a particular
argument.
The previous example used an argument called
cmd
, whose value we could
retrieve thus:
String act = request.getParameter("cmd");
The parameters all come as
String
s. If your arguments are numeric, you'll
have to parse them (and error-check them—HTML forms are, understandably,
weak on validating their input; tons of JavaScript have been written to deal
with this, but this is beyond the scope of this topic.)
Some parameters may have embedded spaces and other special characters
that would disrupt a URL. To deal with that, browsers encode the characters