Reading Form Data
Before delving into how a servlet can read data submitted via a form, it is necessary to understand how data from an HTML form is passed to the webserver by the browser.
Their are too common ways of passing data from the webbrowser to the webserver. They are called POST and GET. Both of these methods pass the data in a 'key=value' format. The key for each data field is specified as part of the tag describing the relevant field.
Using the GET method
(Assume the following form is part of a web page located on the webserver http://www.someserver.com.)
When submitted, the browser would execute the following URL :- http://www.someserver.com/servlets/aservlet?thisIsAKey=xxxx&anotherKey=yyyy
See that the data is appended onto the end of the URL, using a '?' to separate the data from the main body of the URL, with '&' characters used to separate the individual key/value pairs. There is no reason why this URL, with the data appended couldn't be put straight straight into an Anchor tag thus :-
This can enable you to dispense with the need for a form altogether for cases where user input is not required for any of the key/value pairs. eg click here to try out the servlet below using a fixed URL.
Using the POST Method
In some cases it may not be desirable to display all of the data submitted by the user as part of the URL, for example if the user were submitting a password. The POST method of submitting data from a form allows the data to be passed to the webserver seperatly from the URL in a 'hidden' format. Excepting that this method cannot be used to pass key/value pairs from an Anchor tag, this will function in the same way as GET in all other ways.
A Form Reading Servlet
The following code is a simple example of a servlet which is reading parameters that have been supplied by an HTML form.
This servlet interprets information from the following HTML form. It users the POST method, but you can change this to GET if you wish to try both methods. The web page must be located on the same server and accessed via that server (not with a file:open in your browser), or you get '404 file not found' error messages when trying to use it.
When called, this servlet will look for a parameter supplied in the HttpServletRequest called 'yourname' and then construct its reply using the data stored in this parameter. Notice that the 'getParameterValues' method actually returns an array of Strings, rather than a single string. This is because some HTML form elements can return more than one item, eg a list which allows multiple selections.
If you want to try this servlet out, just use the form below :
The information contained in this form will be received by the webserver and passed to the servlet as part of the HttpServletRequest object.
Tims Home Page | Page last modified : 19 May 2003