JSP servlet Basics Getting Started learning: working with form data

Source: Internet
Author: User
Tags array empty html form variables return variable client
js|servlet| data 4.1 Overview of form data

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

"<UL> \ n" +
"<LI> param1:"
+ Request.getparameter ("param1") + "\ n" +
"<LI> param2:"
+ Request.getparameter ("param2") + "\ n" +
"<LI> param3:"
+ Request.getparameter ("param3") + "\ n" +
"</UL> \ n" +
"</BODY> </HTML>");
}

public void DoPost (HttpServletRequest request,
HttpServletResponse response)
Throws Servletexception, IOException {
Doget (request, response);
}
}

   4.3 instance: outputting all the form data

The following example looks for all the variable names sent by the form and puts them in the table, with no values or variables with multiple values highlighted.

First, the program obtains all the variable names through the HttpServletRequest Getparameternames method, and Getparameternames returns a enumeration. Next, the program loops through the enumeration, hasmoreelements to determine when to end the loop, using Nextelement to get the items in enumeration. Since Nextelement returns an object, the program converts it to a string and then uses the string to invoke Getparametervalues.

Getparametervalues returns an array of strings, if the array has only one element and equals an empty string, indicating that the form variable has no value, the servlet outputs "no value" in italics, and if the number of array elements is greater than 1, the form variable has more than one value. The servlet prints these values as an HTML list, and in other cases the servlet puts the value of the variable directly into the table.

Showparameters.java

Note that Showparameters.java used the Servletutilities.java described earlier.

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 (title) + Servletutilities.headwithtitle
"<body bgcolor=\" #FDF5E6 \ ">\n" +
"

"<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> </HTML>");
}

public void DoPost (HttpServletRequest request,
HttpServletResponse response)
Throws Servletexception, IOException {
Doget (request, response);
}
}

Test the form

The following is a form postform.html that sends data to the servlet above. Just like all forms that contain a password input field, the table sends data in the Post method alone. We can see that the simultaneous implementation of Doget and Dopost in the servlet makes the form easier to make.

! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en"
<HTML>
<HEAD>
<TITLE> sample Form </TITLE>
</HEAD>

<body bgcolor= "#FDF5E6" >


<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= "[gv_contenttext]quot;> <BR>
<HR>
The 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 Card number:
<input type= "PASSWORD" Name= "Cardnum" > <BR> <BR>
<CENTER>
<input type= "Submit" value= "Submit order" >
</CENTER>
</FORM>

</BODY>
</HTML>


Related Article

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.