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.

Listing One: An example of a Struts 1.0 validate() method

public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {

ActionErrors errors = new ActionErrors();
if ((player == null) || (player.length() < 1)) {
ActionError playerError = new ActionError(
errors.add(“player”, playerError);
if ((position == null) || (position.length() < 1)) {
ActionError positionError = new ActionError(
errors.add(“position”, positionError);
return errors;

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:

<plug-in className=”org.apache.struts.validator.ValidatorPlugIn”>
value=”/WEB-INF/validator-rules.xml, /WEB-INF/validation.xml”/>

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:

<form name=”savePlayerForm”>
<field property=”player” depends=”required”>
<arg0 key=”label.player”/>
<field property=”position” depends=”required,maxlength”>
<arg0 key=”label.position”/>

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.


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:

type=”org.apache.struts.validator. DynaValidatorForm”>

Leave the Heavy Lifting to Struts

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.

Rogers Cadenhead is a Web application developer and the coauthor of Teach Yourself Java 2 in 21 Days, Third Edition from Sams Publishing. To contact Cadenhead, visit his weblog at http://www.cadenhead.org/workbench. You can download the source code used in this article from http://www.linuxmagazine.com/downloads/2003-04/java.

Comments are closed.