4.12. HTML FORMS AND SERVLET PARAMETERS
59
4.12
HTML Forms and Servlet Parameters
So far we have been forced to pass parameters to a servlet explicitly by encoding
them in a parameter string which we then append to the servlet's URL. In this
section we show how to use the form tags in HTML to do this for us.
HTML forms provide a mechanism for soliciting information from the user
and sending it to the server. Lets first look at a simple example. The following
servlet generates an HTML form the first time the user visits a page. Once the
user fills out the form and presses submit, the data is sent back to the same
servlet which then processes the data. In this case it just computes the age of
the user in millions of seconds!
; ageCalc.servlet
(servlet (age)
(case age
((#null)
{Age Calculator Form
Enter your age in years:
})
(else
{Age Calculator Form
If you are [age] years old, then
Your have lived for
[(* age 365.25 24 60 60 0.000001)]
million seconds
})))
Try this servlet yourself. At age 31 one is about a billion seconds old. The
form element contains attributes that specify which server the information
should be sent to (action) and how the information should be sent (method).
The method can be either get or post. The get method encodes the arguments
into a parameter string which is then attached to the URL, just as we have done
by hand in the previous sections. The post method passes the parameters using
another method in which they do not appear on the URL. This is safer (as the
parameters are not visible on server logs) and allows for larger parameters than
is possible with the get method. The action specifies where the data should be
sent.
Exercise 14 Modify the ageCalc servlet so that it also gets the user's name,
and uses it in the response page.