Working with form data

Source: Internet
Author: User
Tags html form

If you've ever used a web search engine, or viewed an online bookstore, stock price, or ticket information, you might notice odd URLs like "http://host/path?user=Marty+Hall&origin=bwi&dest =lax ". The portion of this URL that follows the question mark, "User=marty+hall&origin=bwi&dest=lax", is the form data, which is the most common way to send Web page data to a server program. For GET requests, the form data is appended to the question mark of the URL (as shown in the previous example), and for post requests, the form data is sent to the server with a separate row.

Previously, extracting the required form variables from this form of data was one of the most troublesome things in CGI programming. First, the data extraction methods for GET requests and post requests are different: for getting requests, the data is typically extracted through the QUERY_STRING environment variable, and for post requests, data is typically extracted from standard input. Second, the programmer must be responsible for truncating the variable name-variable value pairs at the "&" sign, and then separating the variable names (the left of the equals sign) and the variable values (the right side of the equals sign). Third, the value of the variable must be URL-coded. Because when sending the data, letters and numbers are sent in the original form, but the spaces are converted to the plus sign, and the other characters are converted to the "%xx" form, where XX is the character ASCII (or ISO Latin-1) encoded value in hexadecimal notation. For example, if the field value named "Users" in an HTML form is "~hall, ~gates, and ~mcnealy", the actual data sent to the server is "Users=%7ehall%2c+%7egates%2c+and+%7emcnealy". Finally, the fourth reason for the difficulty in parsing the form data is that the value of the variable may be omitted (such as "Param1=val1&param2=&param3=val3"), or a variable may have more than one value, that is, the same variable may appear more than once (such as " Param1=val1&param2=val2&param1=val3 ").

One of the benefits of the Java servlet is that all of the above parsing operations can be done automatically. Simply call the HttpServletRequest GetParameter method, provide the name of the form variable in the invocation parameter (case sensitive), and the GET request and POST request are handled exactly the same way.

The return value of the GetParameter method is a string that is the first occurrence of the variable name specified in the argument, and the corresponding value is encoded by the inverse code (which can be used directly). If the specified form variable exists, but there is no value, GetParameter returns an empty string, or null if the specified form variable does not exist. If the form variable may correspond to multiple values, you can replace the getparameter with Getparametervalues. Getparametervalues can return an array of strings.

Finally, while in practice the servlet is likely to use only those named form variables, in a debug environment it is often useful to get a complete list of form variable names, which can be easily achieved by using the Getparamerternames method. Getparamerternames returns a enumeration in which each entry can be converted to a string that invokes GetParameter.

4.2 Instance: Reading three form variables

The following is a simple example that reads three form variables, param1, param2, and param3, and lists their values as an HTML list. Note that although the answer type (including content type, State, and other HTTP header information) must be specified before the answer is sent, the servlet has no requirement for when to read the request content.

In addition, we can easily make a servlet either to handle a GET request or to process a POST request, either by calling the Doget method in the DoPost method, or by overriding the Service method (service method call Doget, DoPost, Dohead and other methods). This is a standard approach in practical programming, because it requires little extra work, but it can increase the flexibility of client-side coding.

If you are accustomed to using the traditional CGI method to read post data through standard input, then there is a similar method in the servlet, which is to raise the Getreader or getInputStream on HttpServletRequest, But this approach is too cumbersome for ordinary form variables. However, if you want to upload a file, or post data is sent through a dedicated client program instead of an HTML form, you need to use this method.

Note When reading post data using the second method, you cannot use GetParameter to read the data.

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,
Httpservletresp Onse response)
throws Servletexception, IOException {
Response.setcontenttype ("text/html");
PrintWriter out = Response.getwriter ();
String title = "Read three request Parameters";
Out.println Servletutilities.headwithtitle (title) +
" \ n" +
"

" + title + "\ n" + "

    \ n" +
    "
  • param1:"
    + request.getparameter ("param1") + "\ n" +
    "
  • param2:"
    + Request.getparam Eter ("param2") + "\ n" +
  • param3: "
    + request.getparameter (" param3 ") +" \ n "+
    "
\ n "+
" ");
}
public void DoPost (HttpServletRequest request,
HttpServletResponse response)
throws Servletexception , IOException {
Doget (request, response);
}
}
/p>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.