Wizard API updated!
Tim Boudreau has released a new version of the Swing Wizard library (version 0.997) that fixes the WizardException bug reported in JavaWorld's recent Open Source Java Project profile. The article's examples have been reworked to test out the new, improved WizardException. Thanks, Tim, for this helpful fix!
Open Source Java Projects: The Wizard API

Newsletter sign-up

Sign up for our technology specific newsletters.

Enterprise Java
View all newsletters

Email Address:

FacilitatIMe form processing with the Form Processing API 2.0

Explore the new 2.0 features with JSP- and XSLT-based examples

The Form Processing API (FPAPI) represents HTML or other forms using a class named Form. A form consists of one or more form fields, and consequently, class Form has a number of form fields, each represented by class FormElement. As form fields consist of different types, class FormElement resides at the top of the hierarchy of other classes that represent specific form fields.

(I suggest you read the first part of the original "Facilitate Form Processing with the Form Processing API" to fully understand this article; the example of that article no longer applies to the new version.)

With 2.0, that hierarchy is somewhat changed and looks like Figure 1.

Figure 1. Class diagram of form object model. Click on thumbnail to view full-size image.

At the center of this structure is the validate(HttpServletRequest request) method. This method validates all form fields based on criteria that FieldValidator and/or GroupValidator classes attach to each field. (Note that FieldValidator is a new name for 1.0's FieldController; GroupValidator is addressed below.) Thanks to the above class structure, a Form object can fully validate itself, so you can separate that validation from further form processing (in fact, I might have called this API Form Validation API).

In this article, I'll follow a how-to-use approach rather than show how the API works. Using FPAPI 2.0 in a Web application differs from the 1.0 version in three ways:

  1. Designing forms
  2. Presenting forms to the client
  3. Validating fields in a group


Design forms and their fields in XML format

The final task in the form design operation is to create Form objects. In version 1.0, you had to create Form objects by writing Java code (extending class Form). With 2.0, you design forms by writing an XML form designer file called forms.xml; FPAPI then reads that file and creates all Form objects for you.

To create a Form object, the form designer file must define the following:

  • Form name
  • Path to the form's presentation file
  • Path to the form's action
  • Each field (FormElement) the form contains


To create a FormElement object, the form designer file defines the following:

  • Name of class the field belongs to
  • Field name
  • In the case of RadioButtons, CheckBoxes, and MenuBoxes, all possible values those fields can take
  • Field initial value, if any
  • Whether the field is required or not
  • Initial error message, if any
  • Repeated error message, if any
  • FieldValidator object(s), if any
  • GroupValidator object, if any (2.0 only)


To create a FieldValidator or a GroupValidator object, the form designer file defines the following:

  • Full class name
  • Name of a reference variable to the object


A very simple forms.xml file might look like this:

<?xml version='1.0' encoding='utf-8'?>
<forms>
   <forms-field-validator name="postalCodeValidator "
      type="mypackage.PostalCodeValidator"/>
   <form name="myform"
      page="/jsp/myforms/myform.jsp"
      action="/actionPath">
      
      <field name="firstName"
         type="com.codepassion.form.TextBox">
      </field>
  
      <field name="lastName"
         type="com.codepassion.form.TextBox"
         required="true">
      </field>
      
      <field name="postalCode"
         type="com.codepassion.form.TextBox"
         required="true">
         <field-required-message>
            (please fill)
         </field-required-message>
         <field-validator>
            postalCodeValidator
         </field-validator>
      </field>
      <field name="age"
         type="com.codepassion.form.RadioButton">
         <field-value state="selected">
            20-30
         </field-value>
         <field-value>
            30-45
         </field-value>
         <field-value>
            45-60
         </field-value>
      </field>
   </form>
</forms>


You can easily see that each file element defines one item listed above. See the example application's forms.xml in the FPAPI 2.0 download for detailed instructions on using possible elements (tags) and their meaning. FPAPI 2.0 Javadocs also show how to express a class or a method through the form design file.

Present forms to the client

The forms.xml file informs FPAPI how to define forms and their fields, and how to define each field's validation logic. FPAPI uses that information to create the form object model shown in Figure 1.

Class Form is the form object model's central point. All presentation techniques can use Form object as the unique reference for accessing the dynamic pieces of the form's presentation page. The Form class provides this information to the presentation layer in two ways. One way uses the method getFormElements() to return an array of FormElement objects representing all the form's fields. The other way uses the generateXML() or generateXmlAsString() method to return an XML presentation of that information.

The following illustration shows how the generated XML presentation looks:

<form name="formName" >
   <field type="com.codepassion.form.TextBox" >
      <field-name>aFieldName</field-name>
      <field-value>aValueOrNothing</field-value>
      <field-error>anErrorMessageOrNothing</field-error>
   </field>
   <field type="com.codepassion.form.CheckBox" >
      <field-name>aFieldName</field-name>
      <field-value state="checked">aCheckedValue</field-value>
      <field-value state="">anUncheckedValue</field-value>
      <field-value state="checked">aCheckedValue</field-value>
      <field-error>anErrorMessageOrNothing</field-error>
   </field>
   <field type="com.codepassion.form.RadioButton" >
      <field-name>aFieldName</field-name>
      <field-value state="checked">aCheckedValue</field-value>
      <field-value state="">anUncheckedValue</field-value>
      <field-error>anErrorMessageOrNothing</field-error>
   </field>
   <field type="com.codepassion.form.MenuBox" >
      <field-name>aFieldName</field-name>
      <field-value state="">anUnselectedValue</field-value>
      <field-value state="selected">aSelectedValue</field-value>
      <field-value state="">anUnselectedValue</field-value>
      <field-error>anErrorMessageOrNothing</field-error>
   </field>
</form>


Now how do you use this (or the FormElement array) for building the form's presentation? FPAPI's presentation layer materializes through the com.codepassion.form.view.ContentGenerator interface, which has two methods:

   void sendFormContent(HttpServletRequest req, 
      HttpServletResponse resp,
      Form form);
and
   void forwardToFormAction(HttpServletRequest req, 
      HttpServletResponse resp,
      Form form);


FPAPI automatically calls the sendFormContent() method the first time the form is requested and every time the validation doesn't succeed. The sendFormContent() method should read all form data from the Form object (as FormElement objects or as XML format), make them available to the presentation page, and then forward the request to the presentation page.

FPAPI automatically calls the forwardToFormAction() method but only when all field validation succeeds. This method should clean the session from any attributes no longer used and forward the request to the form's action. The form's action here normally maps to your application's controller servlet, which manages further form processing.

You should only have one ContentGenerator class per Web module. The ContentGenerator class's full name is entered through forms.xml's <forms-content-generator> tag.

FPAPI provides one ContentGenerator implementation class, com.codepassion.form.utils.SimpleContentGenerator, which you can use for JavaServer Pages (JSP) presentations. If no <forms-content-generator> element is declared in forms.xml, SimpleContentGenerator is used. See FPAPI 2.0 Javadocs for more information on this class and on the ContentGenerator interface.

Validate fields with GroupValidator interface

Validating fields in a group is a new 2.0 feature. In some situations the validity of one field's value depends on the value(s) of one or more other fields of the same form. The simplest example is a form that has two password fields, one for entering the password, and the other for reentering the same password. These two password fields constitute a validation group, because the validity of an entry in one field depends on the entry to the other field and vice versa. The dependency criteria is values on those two fields must be the same.

Let's take another example. Suppose you have a form that, in addition to other fields, has a "street name" field, a "postal code" field, and a "city" field. Obviously the user enters an address in those fields. Let's also suppose that the user is not required to fill the address information. On the other hand, if he decides to supply the address information, this information should be complete; he should fill in all three fields. These three fields form a validation group; the validation criteria is even if only one field is filled, then all must be filled.

Value dependencies between fields can have infinite variations. Analogous to FieldValidator, FPAPI handles infinite field group variations through the GroupValidator interface. This interface has the method:

   Hashtable getErrorMessages(Hashtable nameValuePairs);


Hashtable nameValuePairs contains as keys, names of fields in the group; and as values, respective field value(s). The returned Hashtable contains as keys, names of fields resulting in an error message; and contains as values, the respective error messages. When validation succeeds (no error messages generated) this method must return null.

The two field group examples are commonly used, which is why FPAPI provides the implementation classes com.codepassion.form.utils.PasswordGroup and com.codepassion.form.utils.SimpleGroup.

1 | 2 | 3 | 4 |  Next >
Resources