CS C395
Dynamic Forms and Validation

Dynamic forms and validation is definitely a useful part of the Sruts framework. The material on it unfortunately is also probably the most badly written part of Cavaness' Programming Jakarta Struts. These notes are meant to complement, not replace, what's in Cavaness. These notes will make no sense on their own.

Using DynaActionForms

DynaActionForm's are meant to solve a simple problem: why define subclass after subclass of ActionForm when most forms are nothing more than a set of simple fields, typically strings?

Using a DynaActionForm instead of a custom subclass of ActionForm is relatively straightforward. You need to make changes in two places:

Defining the <form-bean> in struts-config.xml is straightforward. See pages 191-192 of Cavaness.

In your Action subclass, wherever you used to write things like form.getAuthor() or form.getTitle(), write form.get("author") and form.get("title"). A DynaActionForm implements the Map interface, so get() with a key is used to retrieve data.

Note: Map's get() returns Object, so if you need a String, you need to downcast, e.g.,

 order.setPrice(Double.parseDouble((String) form.get("price")));

Those should be the only changes you need to make to use a DynaActionForm.

Using the Validator

Unfortunately, if you use a DynaActionForm, and you want to validate the field values, you have to create a subclass of DynaActionForm, which is what you were trying to avoid in the first place.

Fortunately, there's a subclass of DynaActionForm that gets validation rules from an XML file. Using this validation framework involves four separate steps:

Cavaness' example of the <plug-in> element on page 268 has a typo. He tells you to create validation.xml, but he wrote validator.xml in the <plug-in>.

To be safe, copy the <plug-in> element from struts-config.xml in the example struts-validator.war file in the Struts home directory.

Similarly, the easiest way to create validation.xml is to copy the <?xml> and !DOCTYPE elements from validation.xml in struts-validator.war. Then create use the following pattern for specifying rules for the fields:

    <form name="form-name">
      <field property="field-name"
        <arg0 key="resource-label"/>
	  ...repeat for each field...

This XML syntax has some of the worst naming conventionsI have seen in 35 years of programming. Just use them, don't try to explain them.

The book shows an example expression for a phone number. There are many online tutorials on regular expressions and many discussions on how to validate an email address, a Zip code, etc. There's also online examples of validation forms here.


Send comments to c-riesbeck@northwestern.edu