Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
70
Chapter 3 Handling the Client Request: Form Data
Figure 3 2
Output of ThreeParams servlet.
3.4 Example: Reading All
Parameters
The previous example extracted parameter values from the form data based
upon prespecified parameter names. It also assumed that each parameter
had exactly one value. Here's an example that looks up all the parameter
names that are sent and puts their values in a table. It highlights parameters
that have missing values as well as ones that have multiple values.
First, the servlet looks up all the parameter names by the
getParameter
Names
method of
HttpServletRequest
. This method returns an
Enumera
tion
that contains the parameter names in an unspecified order. Next, the
servlet loops down the
Enumeration
in the standard manner, using
has
MoreElements
to determine when to stop and using
nextElement
to get
each entry. Since
nextElement
returns an
Object
, the servlet casts the result
to a
String
and passes that to
getParameterValues
, yielding an array of
strings. If that array is one entry long and contains only an empty string, then
the parameter had no values and the servlet generates an italicized No Value
entry. If the array is more than one entry long, then the parameter had multiple
values and the values are displayed in a bulleted list. Otherwise, the one main
value is placed into the table unmodified. The source code for the servlet is
shown in Listing 3.3, while Listing 3.4 shows the HTML code for a front
end that can be used to try the servlet out. Figures 3 3 and 3 4 show the
result of the HTML front end and the servlet, respectively.
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