ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

JavaServer Pages: Generating Dynamic Content
Pages: 1, 2, 3, 4, 5, 6, 7, 8

Setting JavaBeans properties from user input

In this next example, we capture information about web site users. It could be the frontend to a newsletter subscription site, for instance. In order to send the users information that might interest them, we register the birth date, sex, and lucky number, along with the full name and email address, for each person that signs up for the service.

To capture and validate the user input, the example uses a bean named com.ora.jsp.beans.userinfo.UserInfoBean, with the properties described in Table 5-2. If you're a programmer, you may want to skip ahead to peek at the source code for this bean class in Chapter 15.

Table 5-2: Properties fcom.ora.jsp.beans.userinfo.UserInfoBean

Property Name

Java Type

Access

Description

userName

String

read/write

The user's full name

birthDate

String

read/write

The user's birth date in the format yyyy-mm-dd (e.g., 2000-07-07)

emailAddr

String

read/write

The user's email address in the format name@company.com

sex

String

read/write

The user's sex (male or female)

luckyNumber

String

read/write

The user's lucky number (between 1 and 100)

valid

boolean

read

true if the current values of all properties are valid, false otherwise

As shown in the Access column, all properties except valid are read/write properties. This means that, in addition to using the bean's properties to generate output (like in Example 5-1), the property values can be set based on user input.

The HTML form shown in Example 5-2 allows the user to enter information corresponding to the bean properties.

Example 5-2: An HTML Form that Sends User Input to a JSP Page (userinfo.html)

<html>
  <head>
    <title>User Info Entry Form</title>
  </head>
  <body bgcolor="white">
    <form action="userinfo1.jsp" method="post">
      <table>
        <tr>
          <td>Name:</td>
          <td><input type="text" name="userName" >
          </td>
        </tr>
        <tr>
          <td>Birth Date:</td>
          <td><input type="text" name="birthDate" >
          </td>
          <td>(Use format yyyy-mm-dd)</td>
        </tr>
        <tr>
          <td>Email Address:</td>
          <td><input type="text" name="emailAddr" >
          </td>
          <td>(Use format name@company.com)</td>
        </tr>
        <tr>
          <td>Sex:</td>
          <td><input type="text" name="sex" >
          </td>
          <td>(Male or female)</td>
        </tr>
        <tr>
          <td>Lucky number:</td>
          <td><input type="text" name="luckyNumber" >
          </td>
          <td>(A number between 1 and 100)</td>
        </tr>
        <tr>
          <td colspan=2><input type="submit"></td>
        </tr>
      </table>
    </form>
  </body>
</html>

This is a regular HTML page that presents a form with a number of fields, as shown in Figure 5-3. There are a few things worth mentioning here. First, notice that each input field has a name attribute with a value that corresponds to a UserInfoBean property name. Matching the names lets us take advantage of a nice JSP feature that sets property values automatically, as you'll see shortly. Also note that the action attribute of the form specifies that a JSP page, userinfo1.jsp, is invoked when the user clicks the Submit button. Figure 5-3 shows what the form looks like in a browser.

Figure 5-3. User input form

Figure 5-3: User input form  

Example 5-3 shows the JSP page that is invoked when the user submits the form.

Example 5-3: A JSP Page that Validates User Input with a Bean (userinfo1.jsp)

<%@ page language="java" contentType="text/html" %>
<html>
  <body bgcolor="white">
    <jsp:useBean 
      id="userInfo"
      class="com.ora.jsp.beans.userinfo.UserInfoBean">
      <jsp:setProperty name="userInfo" property="*" />
    </jsp:useBean>
 
    The following information was saved:
    <ul>
      <li>User Name: <jsp:getProperty
                       name="userInfo" property="userName" />
      <li>Birth Date: <jsp:getProperty
                        name="userInfo" property="birthDate" />
      <li>Email Address: <jsp:getProperty
                           name="userInfo" property="emailAddr" />
      <li>Sex: <jsp:getProperty
                 name="userInfo" property="sex" />
      <li>Lucky number: <jsp:getProperty
                          name="userInfo" property="luckyNumber" />
    </ul>
    The user input is valid: <jsp:getProperty
                               name="userInfo" property="valid" />
  </body>
</html>

Almost at the top of Example 5-3, you see that a <jsp:useBean> action is used to associate a name with the bean:

<jsp:useBean 
  id="userInfo"
  class="com.ora.jsp.beans.userinfo.UserInfoBean">
  <jsp:setProperty name="userInfo" property="*" />
</jsp:useBean>

The <jsp:useBean> action looks similar to the one in Example 5-1. The id attribute specifies the name for the bean, and the class attribute specifies the full name of the bean class. But here we also use a <jsp:setProperty> action as the body of the <jsp:useBean> action. You must therefore use the complete closing tag (</jsp:useBean>) to tell the JSP container where the action ends, instead of the shorthand notation used in Example 5-1. The body of the <jsp:useBean> action is executed only when a new bean is created. In this example, that's always the case, but as you will learn in Chapter 8, there are cases in which the bean already exists and the action is needed only to associate it with a name.

Now let's take a closer look at the <jsp:setProperty> action. As the name implies, this action is used to set the bean's property values. Like the <jsp:getProperty> action, it has a name attribute that must match the id attribute of a <jsp:useBean> action, and a property attribute that specifies which property to set.

When a form is submitted, the form field values are sent as request parameters with the same names as the form field elements. In Example 5-3, note that an asterisk (*) is used as the property attribute value of the <jsp:setProperty> action. This means that all bean properties with names that match request parameters sent to the page are set automatically. That's why it's important that the form element names match the bean property names, as they do here. Automatically setting all matching properties is a great feature; if you define more properties for your bean, you can set them simply by adding new matching fields in the form that invokes the JSP page.

Besides the property attribute, the <jsp:setProperty> action has two more optional attributes: param and value. If for some reason you can't use the same name for the parameters and the property names, you can use the param attribute to set a bean property to the value of any request parameter:

<jsp:setProperty
  name="userInfo"
  property="userName"
  param="someOtherParam"
/>

Here, the userName property is set to the value of a request parameter named someOtherParam.

You can also explicitly set a bean property to a value that is not sent as a request parameter with the value attribute:

<jsp:setProperty
  name="userInfo"
  property="luckyNumber"
  value="13"
/>

Here, the luckyNumber property is set to the value 13. You typically use the value attribute only when you set the bean properties based on something other than user input, for instance values collected from a database.

Validating user input

Never trust your users, at least not when it comes to entering information in the format you need. Often, you need to make sure the input is valid before you continue to process a request. A date, for instance, can be written in many different formats. If you don't live in the United States, you probably have had to fill out both an I-94 and a customs declaration form to be admitted by an immigration officer. You may have noticed that on one of the forms you need to write your birth date as yyyy/mm/dd and on the other you write it as mm/dd/yyyy. I always get it wrong.

Four of the UserInfoBean's properties require a special format: birthDate, emailAddr, sex, and luckyNumber. A good place to make sure the input is valid is in the bean itself, which is exactly what the UserInfoBean does. With this bean, if you try to set any of the above properties to a value that isn't valid, the bean will leave the property unset. In addition, the bean has a true/false (Boolean) property named valid. This property has the value false unless all other properties have been set to valid values.

Let's see this in action. Example 5-3 displays the property values using the <jsp:getProperty> action:

<li>User Name: <jsp:getProperty
                name="userInfo" property="userName" />

Since a property is set only if the value is valid, no values are shown for improperly specified properties. Try it. Click on the "User Info 1 example" link under the Chapter 5 header in the book examples main page shown in Figure 5-1. Enter both valid and invalid values in the form and look at the result produced by the userinfo1.jsp page when you click Submit. A sample result is shown in Figure 5-4.

Figure 5-4. Output from userinfo1.jsp

Figure 5-4: Output from userinfo1.jsp  

Note that the Birth Date information is missing (at my age, you're not so eager to reveal your birth date), so the input is marked as invalid.

Pages: 1, 2, 3, 4, 5, 6, 7, 8

Next Pagearrow