- A Simple HTML Form
- Using the <tt>request</tt> Object
- Retrieving Form Variables in a Servlet
- Different Ways to Do Forms
- Summary
- Q&A
- Workshop
As you saw in Listing 3.2, the getParameter method in the request object retrieves the values of the form variable. The lone argument to getParameter is the name of the form variable as it was defined in the HTML form, and must match the case exactly. In other words, if you called a form variable firstName in the HTML file, you must pass firstName to getParameter and not firstname or FIRSTNAME.
If you ask the request object for the value of a form variable that does not exist, it returns null. Note that getParameter always returns a string. If you are expecting a number, you have to convert it yourself.
Form Variables: Empty or Null?
There is a difference between a form variable that is empty and a form variable that does not exist. The value of an empty text box is "" (a string with a length of 0). The getParameter method should return null only if a form variable does not exist at all.
Although the term form variable has been used here to describe the parameters passed to the JSP, these parameters technically have nothing to do with forms. When you press the Submit button on an HTML form, the browser encodes the form variables and uses one of two commands to pass them: an HTTP GET command or an HTTP POST command. Without getting down into the nitty-gritty of HTTP, parameters in a GET command are passed in the actual URL, whereas in a POST command they are passed in a different part of the request.
You may notice while surfing the Web that the URL displayed by the browser has a ? and some values of the form name=value separated by & characters. In fact, if you run the example and look at the URL in your browser's address textbox, you can see exactly that. The URL will look something like:
http://localhost:8080/SimpleFormHandler.jsp?firstName=JSP &lastName=Programmer&sex=male&javaType=char
If you wanted to, you could run SimpleFormHandler.jsp directly without going through the initial HTML form. All you would need to do is add the parameters to the end of the URL for your JSP or servlet.
How Special Characters Are Encoded in URLs
URLs have a special encoding for many characters. For example, a space is represented by +. Many characters are represented by % followed by the character's ASCII value in hex. The = sign, for instance, is represented by %3D because its ASCII value is 61 decimal, or 3D hex. You may want to stick to characters and numbers when entering parameters by hand.
Why is this important? Well, it's often necessary to test a form handler, and it is much quicker to manually pass the parameters straight to the form handler than it is to type in the form values every time. Also, because all the form variables are encoded directly into the URL, you can bookmark the JSP in your browser and display the form output whenever you select that bookmark.
Bookmarking a JSP is not always useful, especially when the JSP is just accepting form input. But when the JSP is displaying updated information such as sports scores, weather, stock quotes, or other frequently changing data, bookmarking the page is quite useful. Unfortunately, if the data is sent to the server via an HTTP POST request, bookmarking doesn't work. The bookmark contains only the URL, and when form data is sent via POST, the URL does not include the form data. In the next hour, "How the Browser Interacts with the Server," you'll learn more about the GET and POST request methods.
Handling Multiple Form Values
The browser passes parameters to the server as a series of name=value pairs, as in firstname=Sam or lastname=Tippin. When there are multiple values for the same form variable name, the browser sends multiple name=value pairs. Listing 3.3 shows a simple input form with several text input fields.
Listing 3.3 Source Code for MultiForm.html
<html> <body> <h1>Please enter a list of names</h1> <form action="MultiFormHandler.jsp" method="get"> <input type="text" name="names"><br> <input type="text" name="names"><br> <input type="text" name="names"><br> <input type="text" name="names"><br> <input type="text" name="names"><br> <input type="submit"> </form> </body> </html>
Figure 3.3 shows the form running inside a browser.
Figure 3.3 You can prompt the user with multiple values for the same form variable.
Notice that in Listing 3.3 the names of the fields are the same. If you were to use the getParameter method to fetch the names, you would get only the first one. When you need to fetch multiple parameters, use the getParameterValues method. Listing 3.4 shows a JSP that retrieves the values from the page in Listing 3.3.
Listing 3.4 Source Code for MultiFormHandler.jsp
<html> <body> The names you entered are: < pre> <% // Fetch the name values. String names[] = request.getParameterValues("names"); for (int i=0; i < names.length; i++) { out.println(names[i]); } %> </ pre> </body> </html>
You need to know two things about the getParameterValues method:
If the parameter value doesn't exist at all (that is, there was no form variable with that name), getParameterValues returns null.
If there is exactly one parameter value, you still get back an array. The length of this array is 1.
You usually know the names of all the parameters you are expecting, but for cases where you need to discover the names of all the parameters passed in you can use the getParameterNames method. The method signature for getParameterNames in the request object is
java.util.Enumeration getParameterNames()
The getParameterNames method returns an enumeration of the string objects. Each of these strings is the name of a parameter and can be used as an argument to getParameter or getParameterValues. Listing 3.5 shows a JSP that dumps out the names and values of all the parameters passed to it, including multiple values.
Listing 3.5 Source Code for ShowParameters.jsp
<html> <body> You passed me the following parameters: < pre> <% // Find out the names of all the parameters. java.util.Enumeration params = request.getParameterNames(); while (params.hasMoreElements()) { // Get the next parameter name. String paramName = (String) params.nextElement(); // Use getParameterValues in case there are multiple values. String paramValues[] = request.getParameterValues(paramName); // If there is only one value, print it out. if (paramValues.length == 1) { out.println(paramName+"="+paramValues[0]); } else { // For multiple values, loop through them. out.print(paramName+"="); for (int i=0; i < paramValues.length; i++) { // If this isn't the first value, print a comma to separate values. if (i > 0) out.print(','); out.print(paramValues[i]); } out.println(); } } %> </pre> </body> </html>
Figure 3.4 shows the output from the JSP shown in Listing 3.5. You can easily play around with the ShowParameters JSP by passing parameters without an input form by entering them in the browser's address line. Figure 3.4 illustrates the result of using two parameters in the URL http://localhost:8080/ShowParameters.jsp?param1=One¶m2=Two
Figure 3.4 You can pass parameters to the JSP manually by adding them to the end of the URL.