4.1 overview of form data
If you have used a Web search engine, or browsed online bookstores, stock prices, and air tickets, you may find some strange URLs, such as "http: // host/path? User = Marty + Hall & origin = BWI & DEST = lax ". The part of the URL following the question mark ("user = Marty + Hall & origin = BWI & DEST = lax") is form data, which sends web page data to the server.Program. For GET requests, the form data is appended to the question mark of the URL (as shown in the example above); for post requests, the form data is sent to the server using a separate row.
Previously, extracting the required form variables from this type of data was one of the most troublesome tasks in CGI programming. First, get requests and post requests have different data extraction methods: For GET requests, data is usually extracted using the QUERY_STRING environment variable. For post requests, data is generally extracted using standard input. Second, the programmer must be responsible for truncating the variable name-variable value pair at the "&" symbol, and then separating the variable name (to the left of the equal sign) and variable value (to the right of the equal sign ). Third, URL anti-encoding must be performed on variable values. When sending data, letters and numbers are sent in the original form, but spaces are converted to the plus sign, and other characters are converted to the "% xx" form, XX is the ASCII (or ISO Latin-1) encoded value in hexadecimal notation. For example, if the field value "users" in an HTML form is "~", Hall ,~ Gates, and ~ Mcnealy ", the actual data sent to the server is" users = % 7 ehall % 2C + % 7 egates % 2C + and + % 7emnnaly ". Finally, the fourth cause of the difficulty in parsing form data is that the variable value may be omitted (for example, "param1 = val1 & param2 = & param3 = val3 "), it is also possible that a variable has more than one value, that is, the same variable may appear more than once (for example, "param1 = val1 & param2 = val2 & param1 = val3 ").
One of the advantages of Java Servlet is that all the above parsing operations can be completed automatically. You only need to simply call the getparameter method of httpservletrequest and provide the form variable name (case sensitive) in the call parameters. The GET request and POST request are handled in the same way.
The Return Value of the getparameter method is a string. It is the first time that the variable name specified in the parameter appears, the corresponding value is obtained through reverse encoding (which can be directly used ). If the specified form variable exists but there is no value, getparameter returns an empty string. If the specified form variable does not exist, null is returned. If the form variable may correspond to multiple values, you can use getparametervalues to replace getparameter. Getparametervalues can return a string array.
Finally, although in practical applications, Servlet may only use form variables with known names, it is often useful to obtain a complete list of form variable names in the debugging environment, the getparamerternames method can be used to conveniently achieve this. Getparamerternames returns an enumeration, in which each item can be converted to a string that calls getparameter.
4.2 Example: read three form variables
The following is a simple example. It reads three form variables param1, param2, and param3 and lists their values in the form of an HTML list. Note that although you must specify the response type (including the content type, status, and other HTTP header information) before sending the response content, the servlet has no requirements on when to read the request content.
In addition, we can easily make the servlet to process both get requests and post requests. This only requires the doget method to be called in the dopost method, or overwrite the service method (the service method calls methods such as doget, dopost, and dohead ). In actual programming, This is a standard method, because it requires little extra work, but can increase the flexibility of client encoding.
If you are used to reading post data through standard input using the traditional CGI method, there is also a similar method in servlet, that is, to call getreader or getinputstream on httpservletrequest, however, this method is too cumbersome for common form variables. However, this method is required if you want to upload files or post data through a special client program instead of an HTML form.
Note that getparameter cannot be used to read Post Data in the second method.
Threeparams. Java
Package Hall;
Import java. Io .*;
Import javax. servlet .*;
Import javax. servlet. http .*;
Import java. util .*;
Public class threeparams extends httpservlet {
Public void doget (httpservletrequest request,
Httpservletresponse response)
Throws servletexception, ioexception {
Response. setcontenttype ("text/html ");
Printwriter out = response. getwriter ();
String title = "read three Request Parameters ";
Out. println (servletutilities. headwithtitle (title) +
"<Body> \ n" +
"<H1 align = center>" + title + ""<Ul> \ n" +
"<Li> param1 :"
+ Request. getparameter ("param1") + "\ n" +
"<Li> param2 :"
+ Request. getparameter ("param2") + "\ n" +
"<Li> param3 :"
+ Request. getparameter ("param3") + "\ n" +
"</Ul> \ n" +
"</Body> }
Public void dopost (httpservletrequest request,
Httpservletresponse response)
Throws servletexception, ioexception {
Doget (request, response );
}
}
4.3 instance: Output all form data
In the following example, all the variable names sent by the form are searched and put into the table. Variables with no values or multiple values are highlighted.
First, the program obtains all variable names through the getparameternames method of httpservletrequest. getparameternames returns an enumeration. Next, the program cyclically traverses this enumeration, uses hasmoreelements to determine when to end the loop, and uses nextelement to obtain each item in enumeration. Since nextelement returns an object, the program converts it to a string and then uses this string to call getparametervalues.
Getparametervalues returns a string array. If the array has only one element and is equal to an empty string, this form variable has no value. servlet outputs "no value" in italic format "; if the number of array elements is greater than 1, this form variable has multiple values. servlet outputs these values in the form of an HTML list. In other cases, Servlet directly places the variable values in the table.
Showparameters. Java
Note that showparameters. Java uses the previously introduced servletutilities. java.
Package Hall;
Import java. Io .*;
Import javax. servlet .*;
Import javax. servlet. http .*;
Import java. util .*;
Public class showparameters extends httpservlet {
Public void doget (httpservletrequest request,
Httpservletresponse response)
Throws servletexception, ioexception {
Response. setcontenttype ("text/html ");
Printwriter out = response. getwriter ();
String title = "read all Request Parameters ";
Out. println (servletutilities. headwithtitle (title) +
"<Body bgcolor = \" # fdf5e6 \ "> \ n" +
"<H1 align = center>" + title + ""<Table border = 1 align = center> \ n" +
"<Tr bgcolor = \" # ffad00 \ "> \ n" +
"<TH> parameter name <TH> parameter value ");
Enumeration paramnames = request. getparameternames ();
While (paramnames. hasmoreelements ()){
String paramname = (string) paramnames. nextelement ();
Out. println ("<tr> <TD>" + paramname + "\ n <TD> ");
String [] paramvalues = request. getparametervalues (paramname );
If (paramvalues. Length = 1 ){
String paramvalue = paramvalues [0];
If (paramvalue. Length () = 0)
Out. Print ("<I> no value </I> ");
Else
Out. Print (paramvalue );
} Else {
Out. println ("<ul> ");
For (INT I = 0; I <paramvalues. length; I ++ ){
Out. println ("<li>" + paramvalues [I]);
}
Out. println ("</ul> ");
}
}
Out. println ("</table> \ n </body> }
Public void dopost (httpservletrequest request,
Httpservletresponse response)
Throws servletexception, ioexception {
Doget (request, response );
}
}
Test form
The following figure shows the table form postform.html that sends data to the slave node. Like all forms that contain the password input field, the form uses the POST method to send data. We can see that implementing the doget and dopost methods at the same time in servlet makes form Production easy.
<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en">
<HTML>
<Head>
<Title> example form </title>
</Head>
<Body bgcolor = "# fdf5e6">
<H1 align = "center"> form for sending data using the POST method
<Form action = "/servlet/Hall. showparameters"
Method = "Post">
Item number:
<Input type = "text" name = "itemnum"> <br>
Quantity:
<Input type = "text" name = "quantity"> <br>
Price each:
<Input type = "text" name = "price" value = "$"> <br>
<HR>
First name:
<Input type = "text" name = "firstname"> <br>
Last name:
<Input type = "text" name = "lastname"> <br>
Middle initial:
<Input type = "text" name = "initial"> <br>
Shipping address:
<Textarea name = "Address" rows = 3 Cols = 40> </textarea> <br>
Credit card: <br>
<Input type = "radio" name = "cardType"
Value = "Visa"> visa <br>
<Input type = "radio" name = "cardType"
Value = "Master Card"> Master Card <br>
<Input type = "radio" name = "cardType"
Value = "Amex"> American Express <br>
<Input type = "radio" name = "cardType"
Value = "Discover"> discover <br>
<Input type = "radio" name = "cardType"
Value = "Java smartcard"> JAVA smartcard <br>
Credit Card Number:
<Input type = "password" name = "cardnum"> <br>
Repeat credit card number:
<Input type = "password" name = "cardnum"> <br>
<Center>
<Input type = "Submit" value = "Submit order">
</Center>
</Form>
</Body>
</Html>