HTML forms enable you to submit data to the Web server in a convenient form. As shown in Figure 34.12, the form can contain text fields, text area, check boxes, combo boxes, lists, radio buttons, and buttons .
The HTML code for creating the form in Figure 34.12 is given in Listing 34.3. (If you are unfamiliar with HTML, please see Supplement VII.A, " HTML and XHTML Tutorial .")
1 <!--An HTML Form Demo --> 2 <html> 3 <head> 4 <title> Student Registration Form </title> 5 </head> 6 <body> 7 <h3> Student Registration Form </h3> 8 9 <form action = "http://localhost:8080/liangweb/GetParameters" 10 method = "get"> 11 <!-- Name text fields --> 12 <p> <label> Last Name </label> 13 <input type = "text" name = "lastName" size = "20" /> 14 <label> First Name </label> 15 <input type = "text" name = "firstName" size = "20" /> 16 <label> MI </label> 17 <input type = "text" name = "mi" size = "1" /></p> 18 19 <!-- Gender radio buttons --> 20 <p><label> Gender: </label> 21 <input type = "radio" name = "gender" value = "M" checked /> Male 22 <input type = "radio" name = "gender" value = "F" /> Female </p> 23 24 <!-- Major combo box --> 25 <p><label> Major </label> 26 <select name = "major" size = "1" > 27 <option value = "CS" > Computer Science </option> 28 <option value = "Math" > Mathematics </option> 29 <option> English </option> 30 <option> Chinese </option> 31 </select> 32 33 <!-- Minor list --> 34 <label> Minor </label> 35 <select name = "minor" size = "2" multiple> 36 <option> Computer Science </option> 37 <option> Mathematics </option> 38 <option> English </option> 39 <option> Chinese </option> 40 </select></p> 41 42 <!-- Hobby check boxes --> 43 <p><label> Hobby: </label> 44 <input type = "checkbox" name = "tennis" /> Tennis 45 <input type = "checkbox" name = "golf" /> Golf 46 <input type = "checkbox" name = "pingPong" checked /> Ping Pong 47 </p> 48 49 <!-- Remark text area --> 50 <p> Remarks: </p> 51 <p> <textarea name = "remarks" rows = "3" cols = "56" ></textarea> </p> 52 53 <!-- Submit and Reset buttons --> 54 <p> <input type = "submit" value = "Submit" /> 55 <input type = "reset" value = "Reset" /></p> 56 </form> 57 </body> 58 </html> |
The following HTML tags are used to construct HTML forms:
<form> ... </form> defines a form body. The attributes for the <form> tag are action and method . The action attribute specifies the server program to be executed on the Web server when the form is submitted. The method attribute is either get or post .
<label> ... </label> simply defines a label.
<input> defines an input field. The attributes for this tag are type , name , value , checked , size , and maxlength . The type attribute specifies the input type. Possible types are text for a one-line text field, radio for a radio button, and checkbox for a check box. The name attribute gives a formal name for the attribute. This name attribute is used by the servlet program to retrieve its associated value. The names of the radio buttons in a group must be identical. The value attribute specifies a default value for a text field and text area. The checked attribute indicates whether a radio button or a check box is initially checked. The size attribute specifies the size of a text field, and the maxlength attribute specifies the maximum length of a text field.
<select> ... </select> defines a combo box or a list. The attributes for this tag are name , size , and multiple . The size attribute specifies the number of rows visible in the list. The multiple attribute specifies that multiple values can be selected from a list. Set size to 1 and do not use a multiple for a combo box.
<option> ... </option> defines a selection list within a <select> </select> tag. This tag may be used with the value attribute to specify a value for the selected option (e.g., <option value = "CS">Computer Science ). If no value is specified, the selected option is the value.
<textarea> ... </textarea> defines a text area. The attributes are name , rows , and cols . The rows and cols attributes specify the number of rows and columns in a text area.
Note
It is convenient to place all .html files under the context root directory (e.g., liangweb). Suppose you have placed student_registration_form.html into c:\jakarta-tomcat-5.5.9\webapps\liangweb. You can display it using the URL http://localhost:8080/liangweb/student_registration_form.html |
Tip
If you placed student_registration_form.html into c:\jakarta-tomcat-5.5.9\webapps\liangweb , you can replace http://localhost: 8080 /liangweb/GetParameters in line 9 in the HTML file with /liangweb/GetParameters This is better because it does not reference the port number. If you change the port number, you don't have to modify the HTML file. |
To demonstrate how to obtain parameter values from an HTML form, Listing 34.4 creates a servlet to obtain all the parameter values from the preceding student registration form in Figure 34.12 and display their values, as shown in Figure 34.13. The servlet is named GetParameters and compiled into c:\jakarta-tomcat-5.5.9\webapps\liangweb\WEB-INF\classes. Insert an appropriate servlet entry and a mapping entry into web.xml for the GetParameters servlet.
1 import javax.servlet.*; 2 import javax.servlet.http.*; 3 import java.io.*; 4 5 public class GetParameters extends HttpServlet { 6 /** Process the HTTP Post request */ 7 public void doGet (HttpServletRequest request, HttpServletResponse 8 response) throws ServletException, IOException { 9 response.setContentType( "text/html" ); 10 PrintWriter out = response.getWriter(); 11 12 // Obtain parameters from the client 13 String lastName = request.getParameter( "lastName" ); 14 String firstName = request.getParameter( "firstName" ); 15 String mi = request.getParameter( "mi" ); 16 String gender = request.getParameter( "gender" ); 17 String major = request.getParameter( "major" ); 18 String[] minors = request.getParameterValues( "minor" ); 19 String tennis = request.getParameter( "tennis" ); 20 String golf = request.getParameter( "golf" ); 21 String pingPong = request.getParameter( "pingPong" ); 22 String remarks = request.getParameter( "remarks" ); 23 24 out.println( "Last Name: <b>" + lastName + "</b> First Name: <b>" 25 + firstName + "</b> MI: <b>" + mi + "</b><br>" ); 26 out.println( "Gender: <b>" + gender + "</b><br>" ); 27 out.println( "Major: <b>" + major + "</b> Minor: <b>" ); 28 29 if (minors != null ) 30 for ( int i = ; i < minors.length; i++) 31 out.println(minors[i] + " " ); 32 33 out.println( "</b><br> Tennis: <b>" + tennis + "</b> Golf: <b>" + 34 golf + "</b> PingPong: <b>" + pingPong + "</b><br>" ); 35 out.println( "Remarks: <b>" + remarks + "</b>" ); 36 out.close(); // Close stream 37 } 38 } |
The HTML form is already created in student_registration_form.html and displayed in Figure 34.12. Since the action for the form is http://localhost:8080/liangweb/GetParameters , clicking the Submit button invokes the GetParameters servlet.
Each GUI component in the form has a name attribute. The servlet uses the name attribute in the getParameter(attributeName) method to obtain the parameter value as a string. In case of a list with multiple values, use the getParameterValues(attributeName) method to return the parameter values in an array of strings (e.g., getParameterValues("minor") in line 18).
You may optionally specify the value attribute in a text field, text area, combo box, list, check box, or radio button in an HTML form. For text field and text area, the value attribute specifies a default value to be displayed in the text field and text area. The user can type in new values to replace it. For combo box, list, check box, and radio button, the value attribute specifies the parameter value to be returned from the getParameter and getParameterValues methods . If the value attribute is not specified for a combo box or a list, it returns the selected string from the combo box or the list. If the value attribute is not specified for a radio button or a check box, it returns string on for a checked radio button or a checked check box, and returns null for an unchecked check box.
Note
If an attribute does not exist, the getParameter(attributeName) method returns null . If an empty value of the parameter is passed to the servlet, the getParameter(attributeName) method returns a string with an empty value. In this case, the length of the string is 0. |
This example creates a servlet that processes the GET and POST requests . The GET request generates a form that contains a combo box for locale and a combo box for time zone, as shown in Figure 34.14(a). The user can choose a locale and a time zone from this form to submit a POST request to obtain the current time based on the locale and time zone, as shown in Figure 34.14(b).
Create the servlet named TimeForm in Listing 34.5 and compile it into c:\jakarta-tomcat-5.5.9\webapps\liangweb\WEB-INF\classes . Run the servlet using the URL
http://localhost:8080/liangweb/TimeForm
1 import javax.servlet.*; 2 import javax.servlet.http.*; 3 import java.io.*; 4 import java.util.*; 5 import java.text.*; 6 7 public class TimeForm extends HttpServlet { 8 private static final String CONTENT_TYPE = "text/html" ; 9 private Locale[] allLocale = Locale.getAvailableLocales(); 10 private String[] allTimeZone = TimeZone.getAvailableIDs(); 11 12 /** Process the HTTP Get request */ 13 public void doGet(HttpServletRequest request, HttpServletResponse 14 response) throws ServletException, IOException { 15 response.setContentType(CONTENT_TYPE); 16 PrintWriter out = response.getWriter(); 17 out.println( "<h3>Choose locale and time zone</h3>" ); 18 out.println( "<form method=\" post\ " action=" + 19 "/liangweb/TimeForm>" ); 20 out.println( "Locale <select size=\" 1\ " name=\" locale\ ">" ); 21 22 // Fill in all locales 23 for ( int i = ; i < allLocale.length; i++) { 24 out.println( "<option value=\"" + i +" \ ">" + 25 allLocale[i].getDisplayName() + "</option>" ); 26 } 27 out.println( "</select>" ); 28 29 // Fill in all time zones 30 out.println( "<p>Time Zone<select size=\" 1\ " name=\" timezone\ ">" ); 31 for ( int i = ; i < allTimeZone.length; i++) { 32 out.println( "<option value=\"" + allTimeZone[i] +" \ ">" + 33 allTimeZone[i] + "</option>" ); 34 } 35 out.println( "</select>" ); 36 37 out.println( "<p><input type=\" submit\ " value=\" Submit\ " >" ); 38 out.println( "<input type=\" reset\ " value=\" Reset\ "></p>" ); 39 out.println( "</form>" ); 40 out.close(); // Close stream 41 } 42 43 /** Process the HTTP Post request */ 44 public void doPost(HttpServletRequest request, HttpServletResponse 45 response) throws ServletException, IOException { 46 response.setContentType(CONTENT_TYPE); 47 PrintWriter out = response.getWriter(); 48 out.println( "<html>" ); 49 int localeIndex = Integer.parseInt( 50 request.getParameter( "locale" )); 51 String timeZoneID = request.getParameter( "timezone" ); 52 out.println( "<head><title>Current Time</title></head>" ); 53 out.println( "<body>" ); 54 Calendar calendar = 55 new GregorianCalendar(allLocale[localeIndex]); 56 TimeZone timeZone = TimeZone.getTimeZone(timeZoneID); 57 DateFormat dateFormat = DateFormat.getDateTimeInstance( 58 DateFormat.FULL, DateFormat.FULL, allLocale[localeIndex]); 59 dateFormat.setTimeZone(timeZone); 60 out.println( "Current time is " + 61 dateFormat.format(calendar.getTime()) + "</p>" ); 62 out.println( "</body></html>" ); 63 out.close(); // Close stream 64 } 65 } |
When you use the URL http://localhost:8080/liangweb/TimeForm , the servlet TimeForm 's doGet method is invoked to generate the time form dynamically. The method of the form is POST, and the action invokes the same servlet, TimeForm . When the form is submitted to the server, the doPost method is invoked to process the request.
The variables allLocale and allTimeZone (lines 9 “10), respectively, hold all the available locales and time zone IDs. The names of the locales are displayed in the locale list. The values for the locales are the indexes of the locales in the array allLocale . The time zone IDs are strings. They are displayed in the time zone list. They are also the values for the list. The indexes of the locale and the time zone are passed to the servlet as parameters. The doPost method obtains the values of the parameters (lines 49 “51) and finds the current time based on the locale and time zone.
Note
If you choose an Asian locale (e.g., Chinese, Korean, or Japanese), the time will not be displayed properly because the default character encoding is UTF-8. To fix this problem, add the following statement in line 48 to set an international character encoding: response.setCharacterEncoding( "GB18030" ); For information on encoding, see §26.6, "Character Encoding." |