Users Type the Darndest Things

During his television and writing career, Art Linkletter perfected the art of eliciting unexpected and humorous responses from children. For example, when asked how his parents met, one eight-year-old boy replied, "My father was doing some strange chores for my mother. They won't tell me what kind." Indeed, as Linkletter said, "Kids say the darndest things!"

During his television and writing career, Art Linkletter perfected the art of eliciting unexpected and humorous responses from children. For example, when asked how his parents met, one eight-year-old boy replied, “My father was doing some strange chores for my mother. They won’t tell me what kind.” Indeed, as Linkletter said, “Kids say the darndest things!”

Today, if Linkletter were a Web programmer, he’d probably say, “Users type the darndest things!” However, he wouldn’t be laughing. Validating user input — necessary to prevent bad form data from crashing applications, polluting databases, or causing other harmful side effects — is one of the most time-consuming, tedious, and thankless tasks in Web programming.

Thankfully, the new version of Jakarta Struts (described in last month’s issue or available online at http://www.linux-mag.com/2002-03/struts.html) supports an innovative (and arguably easier) way to check user input: the Commons Validator. The Validator allows you to validate form data declaratively, using an external, XML configuration file instead of Java code. By excising validation from your application, you can make changes to your form and to the associated validation method without recompiling your code. Even better, the Validator can be used on any Java project — on or off the Web.

This month, let’s continue looking at Struts 1.1 and take an in-depth look at the Validator. If you don’t have Struts yet, you can download it and its extensive set of documentation from http://jakarta.apache.org/struts.

Doing It the Old-Fashioned Way

Prior to Struts 1.1, you’d validate input in a Struts application by placing application-specific code in the validate() method of an ActionForm. Each ActionForm, commonly referred to as a form bean, captured and (temporarily) stored form data so validate() could verify the input. If your validate() code found anything amiss, it would create and return one or more ActionErrors. The ActionErrors, in turn, could be used to tell the user what was wrong.

For example, the validate() method in Listing One checks that both fields in the form, player and position, have some data.

The use of validate() in form beans continues to be supported in Struts 1.1, but there are two substantial drawbacks to their use. First, because validation is handled in Java code, any change to the form or how input is validated requires recompilation. Also, because the same kinds of user input may be collected at several different places in an application, there can be considerable redundancy in different form beans.

Delegate, Delegate, Delegate

Using the Commons Validator, you can delegate the entire chore of validation to the Struts framework. All you need to do is enable the Validator using the Struts plug-in architecture and configure two XML files, validation.xml and validator-rules.xml, in your application’s WEB-INF folder.

To enable the Validator, add a <plug-in> tag to the end of the application’s struts-config.xml file, right before the closing </struts-config> tag:

The value attribute of the <set-property> tag identifies the two XML files that contain the validation rules for the application.

One of those files, validator-rules.xml, contains generic validation rules that can be used in any application. There are eighteen rules that perform a variety of sanity checks. For example, required makes sure that a field has not been left blank; maxlength ensures that a field is a specified length (or shorter); and byte ensures the field is a valid byte value. By design, there’s no need to change the standard validation-rules.xml file to configure an application — it can be used without modification on numerous projects.

The second file listed in the <plug-in> tag, validation.xml, contains the specific validation rules for your application. In the file, a validation rule is expressed using the <form> element:

The <form> element should contain one <field> element for each form field you want validated. The field’s name is indicated by the property attribute and it must match the name used on the Web form and in other configuration files for the application.

The <form> element’s depends attribute establishes one or more validation rules that apply to the field. These rules are referenced by their names — such as required, email, and mask. If more than one rule applies, separate each rule in the series by commas.

When the Validator checks a field for multiple rules, it progresses from left to right and quits at the first failure, creating an ActionError with details about what went wrong. The <arg0> element contained in <field> provides information to make an error more descriptive; there also are arg1, arg2, and arg3 elements to provide even more.

In this example, arg0 has a key attribute containing the label of the field, which presumably has been defined in the application’s resource bundle.

DynaForms

The Commons Validator can be combined with another feature of Struts, DynaForms, to obsolete ActionForm entirely.

A DynaForm object is a Struts form that leverages the runtime bean support found in the Apache Commons Beanutils project. Beanutils supports JavaBeans that use Java’s reflection and introspection capabilities to discover and use the properties of the bean. These souped-up beans are often called dynabeans.

Unlike a JavaBean that requires explicit get() and set() methods for each property of the bean — such as getPlayer() and setPlayer() or getPosition() and setPosition() — DynaForm classes implement the DynaBean interface, supporting generic set() and get() methods that specify a property as an argument. The get() method returns an Object that must be cast to the proper type.

To use dynabeans in Struts, a form bean’s tag in the struts-config.xml file must include <form-property> tags that identify the name and type of each property of the bean:

Creating a Struts application can seem strange to a Java programmer accustomed to doing all of a project’s heavy lifting in code. Making the most out of Struts requires thorough knowledge of the interactions between the framework classes, XML configuration files, a servlet engine’s configuration files, and the Web application’s own classes.

To help you get started with Struts and the Common Validator, you can find the code from Listing One and additional code for a guest book application online at http://www.linux-mag.com/downloads/2003-04/java. That URL also contains a WAR file with the complete project.

Although the Commons Validator is popular enough to have found its way into the main Struts release, developers should evaluate whether the Validator is a help or hindrance before incorporating it into their own efforts. Some programmers will find it much easier to relegate input validation to XML files where it can be adjusted without touching any classes. Others will prefer to handle it in Java code.

After several months on the cutting edge of Java development, next month’s column will travel back into Java’s distant past — all the way back to 1995 — to rediscover the lost art of designing Java applets.

Advertiser Disclosure:
Some of the products that appear on this site are from companies from which QuinStreet receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. QuinStreet does not include all companies or all types of products available in the marketplace.