About Java and JRuby Development
JEE, Spring, Guice
Hibernate, Java Persistence (JPA)
and various Web Frameworks

Struts ValidatorActionForm using an example application

This tutorial explains the usage of the
Struts form bean ValidatorActionForm
using a working example.

Generals

Autor:

Sascha
Wolski

Sebastian
Hennebrüder

http://www.laliluna.de/tutorials.html

Date: February, 16th 2005


Dependencies

Struts 1.1



Jboss, Tomcat, Jetty etc


PDF
download:
http://www.laliluna.de/download/struts-validatoraction-form-en.pdf


Source
download:
http://www.laliluna.de/download/struts-validatoraction-form-source.zip






ValidatorActionForm
class


The
form bean class
ValidatorActionForm extends the ValidatorForm
class.


It
has the capacity to validate fields of a form using validation rules
which are defined in an XML file.

There
is one difference between these classes. The validation rules of a
ValidatorActionForm are not assigned to the action form but to the
action. (/path-to-action/action.do).

So
it is possible to reuse a bean in multiple actions but to define
different validations for each action.



For the FormBean class a name is defined in
the Struts Config.

Example:

<form-beans >
	<form-bean name="exampleForm" type="my.package.ExampleForm" />
</form-beans>




The form bean can than be reused in an
action definition. Below you see an example for an ActionMapping in
the Struts Config.


Example:


<action attribute=“exampleForm”
input=“/form/example.jsp”
name=“exampleForm”
path=“/example”
scope=“request”
type=“my.package.ExampleAction” />





Validation of properties


The form bean ValidatorActionForm
uses the Struts validation capabilities using
validation rules defined in XML files. Struts offers a wide choice of
rules, you can all find in the file validator-rules.xml.

You configure the rules for
each property of a FormBean. These validations have to be written in
the XML file (validation.xml)

Example validation file
validation.xml:

&lt;form-validation&gt;
 &lt;formset&gt;
        &lt;!-- validation mapping f�r example action --&gt;
        &lt;form name="/example"&gt;
            &lt;field 
            	property="name"
                depends="required, minlength"&gt;
                	&lt;arg0 key="exampleForm.name" /&gt;
                	&lt;arg1 key="${var:minlength}" resource="false" /&gt;
			        &lt;var&gt;
			          &lt;var-name&gt;minlength&lt;/var-name&gt;
			          &lt;var-value&gt;3&lt;/var-value&gt;
			        &lt;/var&gt;
            &lt;/field&gt;
 	 &lt;/form&gt;
    &lt;/formset&gt;
&lt;/form-validation&gt;

Initializing the properties


The ValidatorActionForm
class offers a reset method which is called automatically by Struts.
In this method you can initialize properties.


Example:


public void reset(ActionMapping mapping, 
HttpServletRequest request) {

//Initialisieren der Eigenschaft text
text = “Hello World”;
}





Working example of a ValidatorActionForm
Beans


We will show you the usage of an
ValidatorActionForm
Bean using a simple working example.



Creating
a ValidatorActionForm
class


Create a bean form class ExampleForm
in a package.
(Example:
de.laliluna.tutorials.validatoractionform.form).

The class extends the ValidatorActionForm.



Create two properties name of type String and age of type int.



Create getters and setters for your properties.



The class looks like the following.


public class ExampleForm extends ValidatorActionForm {

//Eigenschaften der Klasse
private String name;
private int age;

//Getter und Setter Methoden
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}





Creating an Action class


Create a new class of type ExampleAction in
the package de.laliluna.tutorial.validatoractionform.action.


The class extends the Action class of
Struts.


Implement the execute(..) method
and output the variables
.


The
following is the source code of the class
ExampleAction


public class ExampleAction extends Action {

public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {

//ValidatorActionForm zuweisen
ExampleForm exampleForm = (ExampleForm) form;

//Zugriff auf Eigenschaften der ValidatorActionForm
//Klasse innerhalb der Action Klasse
System.out.println(exampleForm.getName());
System.out.println(exampleForm.getAge());

return mapping.findForward(“success”);
}

}


Create the JSP files


Create two new JSP files named example1.jsp
and
example2.jsp in
the directory
../WebRoot/form/ .


Below you can see
the source code. It is apart from a simple difference the same.


Change the value
of <html:form action=�..�> in the first JSP to
/example1 and in the second JSP to /example2.


<%@ page language=“java”%>
<%@ taglib uri=“http://jakarta.apache.org/struts/tags-bean” prefix=“bean”%>
<%@ taglib uri=“http://jakarta.apache.org/struts/tags-html” prefix=“html”%>

<html>
<head>
<title>JSP for exampleForm</title>
</head>
<body>
<html:form action=“/example1”>
<html:errors />
Name: <html:text property=“name” /> <br>
Age: <html:text property=“age” /> <br>
<html:submit value=“Send”/>
</html:form>
</body>
</html>






Configure the form bean (struts-config.xml)


Open the struts-config.xml and add
your form bean definition between the <form-bean>,

The attribute name defines the name
of the form bean. Other action can refer to the form bean using this
name.

type defines the form bean class. In
our case it is ValidatorActionForm.

&lt;form-beans &gt;
	&lt;form-bean name="exampleForm" type="de.laliluna.tutorial.validatoractionform.form.ExampleForm" /&gt;
&lt;/form-beans&gt;




Create two action mappings (struts-config.xml)


We will create two action mappings to show
the usage of the ValidatorActionForm class. Both actions will use the
same form bean.


As we are lazy we will also use the same
action class ExampleAction.


Create the action mappings in between the
<action-mappings> tags. Use the form bean exampleForm
and forward to the JSP files.


The first action mapping has the path
/example1,
the second one /example2.


name
is the name of the form bean


input defines the JSP which is shown
when an error occured during the validation. In our case this is the
same JSP we used to show the form.


type defines the action class which
is called for the action


<forward …>
defines the forwards of the action. Here the JSP file are
example1.jsp and example2.jsp.


<action-mappings >
<action
attribute=“exampleForm”
input=“/form/example1.jsp”
name=“exampleForm”
path=“/example1”
scope=“request”
type=“de.laliluna.tutorial.validatoractionform.action.ExampleAction”>
<forward name=“showExample” path=“/form/example1.jsp” />
</action>

<action attribute=“exampleForm” input=“/form/example2.jsp” name=“exampleForm” path=“/example2” scope=“request” type=“de.laliluna.tutorial.validatoractionform.action.ExampleAction”> <forward name=“showExample” path=“/form/example2.jsp” /> </action> </action-mappings>





Initializing
the ValidatorActionForm
class


Add
a reset method in the ValidatorActionForm class
ExampleForm . Initialize the
form properties in this method.

public void reset(ActionMapping mapping, <br> 	HttpServletRequest request) {<br><br> 	//Initialisieren der Eigenschaften<br> 	name = "Adam Weisshaupt";<br> 	age = 23;<br>}

Validating properties with XML validation rules


To validate the user input, if a
name’s length is greater than 3 character or the age is between 0 and
150, you have to configure this validations in an XML file.


Create the XML file validation.xml in the
directory
/WebRoot/WEB-INF/.

<form
name=�..�>
defines the Form Bean to which the validations
are applied.

<field property=�..�>
defines a property of a form bean. The attribute
depends
configures the used rule from the Struts rule set. (All rules are
defined in the validator-rules.xml ).

<arg0
key=�..�>
defines a parameter which is passed to the error
message. In the error message for intRange, there is one parameter
expected. (more informations at MessageResouce).

<var-name>
sets the name of the variable used in the validation rule and
<var-value> the value of the variable.

We will
create validation rules for each mapping.


&lt;form-validation&gt;
    &lt;formset&gt;
        &lt;!-- validation mapping for action /example1 --&gt;
        &lt;form name="/example1"&gt;
            &lt;field 
            	property="name"
                depends="required, minlength"&gt;
                	&lt;arg0 key="exampleForm.name" /&gt;
                	&lt;arg1 key="${var:minlength}" resource="false" /&gt;
			        &lt;var&gt;
			          &lt;var-name&gt;minlength&lt;/var-name&gt;
			          &lt;var-value&gt;3&lt;/var-value&gt;
			        &lt;/var&gt;
            &lt;/field&gt;
            &lt;field
                property="age"
                depends="required, intRange, integer"&gt;
                    &lt;arg0 key="exampleForm.age"/&gt;
                    &lt;arg1 name="intRange" key="${var:min}" resource="false" /&gt;
        		  &lt;arg2 name="intRange" key="${var:max}" resource="false" /&gt;
                    &lt;var&gt;
			  	&lt;var-name&gt;min&lt;/var-name&gt;
			      &lt;var-value&gt;1&lt;/var-value&gt;
			  &lt;/var&gt;
			  &lt;var&gt;
			      &lt;var-name&gt;max&lt;/var-name&gt;
			      &lt;var-value&gt;150&lt;/var-value&gt;
			  &lt;/var&gt;
            &lt;/field&gt;
        &lt;/form&gt;
 
        &lt;!-- validation mapping for action /example2 --&gt;
        &lt;form name="/example2"&gt;
            &lt;field 
                property="name"
                depends="required, minlength"&gt;
                  &lt;arg0 key="exampleForm.name" /&gt;
                	&lt;arg1 key="${var:minlength}" resource="false" /&gt;
			&lt;var&gt;
				&lt;var-name&gt;minlength&lt;/var-name&gt;
			      &lt;var-value&gt;6&lt;/var-value&gt;
			&lt;/var&gt;
            &lt;/field&gt;
        &lt;/form&gt;
    &lt;/formset&gt;
&lt;/form-validation&gt;




Configure the ValidatorPlugins in the Struts
Config file


In order to use the Struts-Validator
you must add the ValidatorPlugin in the Struts Config. Otherwise
Struts does not know your validation files and will not use them.


Open the struts-config.xml and add
the following properties to the end of the struts config file.into
the tag <struts-config> .


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


Create a Message Resource file


The Message Resource file is needed
for the output of the error messages, we used in the execute method.

Create a new file named
ApplicationResources.properties in the package
de.laliluna.tutorial.validatoractionform.

You can find more information about
message resource files in our Message Resource tutorial.

http://www.laliluna.de/articles/posts/struts-message-resources-tutorial.html

Add
the following to the file
:

errors.suffix=&lt;br&gt;
# -- default error messages for struts validator
errors.required='{0}' is required.
errors.minlength='{0}' can not be less than {1} characters.
errors.range='{0}' is not in the range {1} through {2}.
# -- field names
exampleForm.name=Name
exampleForm.age=Age




Open the struts-config.xml
and add the following lines to configure your resource file.


<message-resources parameter=“de.laliluna.tutorial.validatoractionform.ApplicationResources”/>





Test your example


We have finished our example
application. Test the example by calling

http://localhost:8080/ValidatorActionForm/example1.do

(Validation of name and age)

http://localhost:8080/ValidatorActionForm/example2.do

(validation of name)