Getting Started with the Validator Framework

 < Day Day Up > 



The hardest part of the Validator Framework, as with many things, is just getting started. The validator.xml file can be especially intimidating, but after working with it on a few projects, I began to wonder how I had ever implemented validation without the framework. To reduce the learning curve, let's walk through using the Validator Framework step by step.

The easiest way to get started with the Validator Framework is to create a simple form. This example creates a user registration form. As part of this user registration, you want the end user to enter a username, which should consist of at least five characters.

The following ten steps are the same standard steps you would follow to create any form:

  1. Create an ActionForm class (InputForm.java).

  2. Create an Action (InputAction).

  3. Set up a resource bundle for the application in the Struts configuration file.

  4. For internationalization (I18N) purposes, add a label for the userName field to the resource bundle.

  5. Create an input JSP (input.jsp).

  6. Add a form to the input JSP.

  7. Add a field to the form for the username.

  8. Add a label to the field that references a string in the resource bundle.

  9. Add the form bean declaration to the Struts configuration file.

  10. Add the Action mapping for this form to the Struts configuration file.

To use the Validator Framework, follow these additional steps:

  1. Add the Validator Plugin to the Struts configuration file.

  2. Copy the validator-rules.xml and validator.xml files into WEB-INF (from the blank Struts Web application).

  3. Change the ActionForm class (InputForm.java) to the subclass ValidatorForm (org.apache.struts.validator.ValidatorForm).

  4. Add a form to the form set in the validator.xml file.

  5. Add a field to the form declaration in the validator.xml file corresponding to the userName field.

  6. Specify that the userName field correspond to the minlength rule.

  7. Add the error message for the minlength rule to the resource bundle.

  8. Specify that the username label be the first argument to the error message.

  9. Configure the value of the minlength value to 5.

  10. Specify that the value of the rules' minlength variable be the second argument to the error message.

Understanding the Standard Steps

Let's begin by examining the standard steps for creating a form; then in the following section we will discuss the steps specific to the Validator Framework.

Step 1 is to create an ActionForm that will hold the username as a property:

 public class InputForm extends ActionForm {      public String userName;      public String getUserName() {           return userName;      }      public void setUserName(String string) {           userName = string;      } } 

In step 2, you to create an Action (InputAction):

 public class InputAction extends Action {      public ActionForward execute(           ActionMapping mapping,           ActionForm form,           HttpServletRequest request,           HttpServletResponse response)           throws Exception {                InputForm inputForm = (InputForm) form;                System.out.println(inputForm.getUserName());                return mapping.findForward("success");      } } 

The above code snippet shows a simple Action that prints out the value of userName from the InputForm to standard out.

Step 3 sets up a resource bundle for the application in the Struts configuration file. To internationalize the labels for our fields, you need to set up a resource bundle to contain the labels. Add the following entry to the Struts configuration file (struts-config.xml), just after the last Action mapping:

 <message-resources parameter="ch12.application"/> 

Step 4 involves adding a label for the userName field to the resource bundle. Based on the previous step, you find the resource bundle in WEB-INF/classes/ch12/application.properties. Add an entry to this file for the userName field:

 inputForm.userName=User Name 

If you had property files for a specific locale, you would have to create a properties file and make entries in that file for that locale—for example, WEB-INF/classes/ch12/application_fr.properties for the French language. Refer to Chapter 9, "Internationalizing Your Struts Applications," for more details.

start sidebar

It is a standard convention to use the form name, plus dot, plus the property name for the key of the message in the properties file.

end sidebar

Step 5 is to create an input JSP (input.jsp). Now that you have created the Action form, you create an input JSP that uses the Action form (input.jsp) as shown in Listing 12.1

Listing 12.1: The input JSP that uses the Action form (input.jsp).

start example
 <%@ taglib uri="struts-html"  prefix="html" %> <%@ taglib uri="struts-bean"  prefix="bean" %> <%@ taglib uri="struts-logic" prefix="logic" %> <html> <body> <logic:messagesPresent> There were errors <ul> <font color='red' > <html:messages >   <li><%= error %></li> </html:messages> </font> </ul> </logic:messagesPresent> <html:form action="inputSubmit">  <bean:message key="inputForm.userName"/>  <html:text property='userName'/> <br />  <html:submit value="ok"/> </html:form> </body> </html> 
end example

The above JSP page still has some static text strings. In order to implement i18n, you will need to replace all static text with bean:messages. Thus, you would have to replace the text "There were errors".

 Adding a form to the input JSP is step 6: <html:form action="inputSubmit"> ... </html:form> 

Step 7 involves adding a field to the form for the username:

 <html:form action="inputSubmit">   <html:text property='userName'/> <br /> </html:form> 

In step 8, you add a label to the field that references a string in the resource bundle:

 <html:form action="inputSubmit">  <bean:message key="inputForm.userName"/>  <html:text property='userName'/> <br />  </html:form> 

Notice we use inputForm.userName as the key that defines the label. This pulls the string associated with this key out of the resource bundle you defined earlier. Keep this in mind; you use this same label later to refer to the field when you print an error message.

In step 9, you add the form bean declaration to the Struts configuration file:

   <form-beans>         <form-bean             name="inputForm"             type="ch12.InputForm"/>   </form-beans> 

The name of the form bean is used in the validation.xml file to refer to this particular form (inputForm).

Finally, in step 10 you add the Action mapping for this form to the Struts configuration file:

   <action-mappings>         <action             path="/inputSubmit"             type="ch12.InputAction"             name="inputForm"             scope="request"             validate="true"             input="/input.jsp">          <forward name="success" path="/success.jsp"   />        </action>   </action-mappings> 

Note that this Action mapping uses the Action form that we defined earlier. Also note that validation is turned on so that the execute method will not be invoked until the Action form validates. Now we must examine how the sample application is structured so that we can set the context for configuring a validation rule for the userName property.

Understanding the Validator Framework

In this section, we add support for validation of the username with the Validator Framework.

Step 1 is to add the Validator Plugin to the Struts configuration file. The Validator Framework integrates with Struts via this Plugin, which is responsible for reading the configuration files for the Validator rules. To use the Validator Framework with Struts, you need to add this Plugin after any message resource elements in the Struts configuration file as follows:

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

In step 2, you copy the validator-rules.xml and validator.xml files into WEB-INF (from the blank Struts web application). The validator-rules.xml file serves as the deployment descriptor for validation rule components. This example uses a preexisting validation rule component so that you do not have to modify the validator-rules.xml file. The validator.xml file enables you to set up the mappings from the Action form's property to the rules and any error message for the rules. Examples of both the validator-rules.xml file and the validator.xml file are in the blank starter Web application that ships with Struts.

Step 3 is to change the ActionForm class (InputForm.java) to the subclass ValidatorForm (org.apache.struts.validator.ValidatorForm). The Validator Framework includes its own custom ActionForm called ValidatorForm. The ValidatorForm overrides the validate method of the ActionForm and communicates with the framework to validate the fields of this form. Here are the changes you need to make to InputForm.java:

 ... import org.apache.struts.validator.ValidatorForm; ... public class InputForm extends ValidatorForm {      public String userName;      public String getUserName() {           return userName;      }      public void setUserName(String string) {           userName = string;      } } 

Step 4 is adding a form to the form set in the validator.xml file. You must add the mapping from the inputForm bean definition in the struts-config.xml file to the rules that should be invoked for the individual properties of the inputForm bean:

     <formset>           <form name="inputForm">            ...           </form>     </formset> 

This code states that you are going to write rules for the properties of the form bean whose name is inputForm as defined in the struts-config.xml. The name has to match the name of the form bean you defined in the struts-config.xml file earlier.

In step 5, you add a field to the form declaration in the validator.xml file corresponding to the userName field. Now that you specified which form you want to associate with rules, you can start associating fields (also known as bean properties) with the predefined rules: The field sub-element maps inputForm's userName property to one or more rules.

           <form name="inputForm">                <field property="userName"                        depends="minlength">                        ...                </field>           </form> 

Step 6 is to specify that the userName field correspond to the minlength rule:

           <form name="inputForm">                <field property="userName"                        depends="minlength">                        ...                </field>           </form> 

The depends attribute of the field element takes a comma-delimited list of rules to associate with this property. Therefore, this code associates the userName property with the minlength rule. The minlength rule is one of the many rules built into the Validator Framework. This rule is associated with a minlength rule handler and an error message key. If you looked up the minlength rule in the validator-rules.xml file you would see the following:

       <validator name="minlength"             classname="org.apache.struts.validator.FieldChecks"                method="validateMinLength"                ...               depends=""                   msg="errors.minlength">       ...       </validator> 

Notice that the validator element defines the minlength rule. It also uses the classname attribute to specify the rules handler. In our example, the handler for this rule is implemented in the class org.apache.struts.validator.FieldChecks by the validateMinLength method. The msg attribute specifies the key for the message that the framework will look up in the resource bundle to display an error message if the associated fields do not validate.

In step 7, you add the error message for the minlength rule to the resource bundle. Because you are using the minlength rule, you must import its associated message into the resource bundle for this Web application. The validator-rules.xml file has sample messages for all of the rules in a commented section. Find the message errors.minlength in the comments, and cut and paste it to the application.properties file as follows:

 inputForm.userName=User Name errors.minlength={0} can not be less than {1} characters. 

You specify that the username label is the first argument to the error message in step 8. Notice that the errors.minlength message takes two arguments. The first argument is the name of the field as it appears to the end user. The second argument is the value of the minlength variable (we set this second argument later). To set up the first argument, use the arg0 element as follows:

 <form-validation>     <formset>           <form name="inputForm">                <field property="userName"                        depends="minlength">                     <arg0 key="inputForm.userName"/> ...                </field>           </form>      </formset> </form-validation> 

The arg0 element passes the key of the message resource. Therefore, in this example the error message will display the inputForm.userName message, which you set to User Name in step 4 of setting up a standard form (see the previous section "Understanding the Standard Steps").

In step 9, you configure the value of the minlength value to 5. Rules take parameters. This particular rule takes a parameter that tells it what the numeric value of the minimum length is. To set a parameter you use the var element as follows:

      ...            <field property="userName"                         depends="minlength">                        ...                      <var>                           <var-name>minlength</var-name>                           <var-value>5</var-value>                      </var>            </field>      ... 

The var element has two sub-elements that specify the name of the parameter and the value of the parameter.

Finally, in step 10 you specify that the value of the rules' minlength variable is the second argument to the error message. As you recall, earlier you specified that the second argument to the error message be the value of the minlength parameter. Therefore, instead of getting the argument from the resource bundle, you want to get it from the variable that you just defined. To do this, you must specify another argument. This time, use the arg1 element:

           <form name="inputForm">                <field property="userName" ...                     <arg1 key="${var:minlength}"                             name="minlength"                             resource="false"/>                     <var>                          <var-name>minlength</var-name>                          <var-value>5</var-value>                     </var> 

Notice that the code sets the resource attribute equal to false, which means that the second argument will not be looked up in the resource bundle. Instead, the second argument will use the minlength parameter defined in the previous step. To do this, the key attribute is set to $(var:minlength), which essentially states that the value of the second argument is equal to the value of the minlength parameter.

The name attribute states that this second argument is appropriate only for the minlength rule. Thus, the second argument will be the value of the minlength parameter if there is a validation problem with the minlength rule. Remember that the property can be associated with many rules because the depends attribute of the field element takes a comma-delimited list of rules to associate with the property. Therefore, the name attribute specifies which rule this argument is used with.

You may be thinking that you have to do a lot of work to use the Validator Framework. However, once you set up the framework, using additional rules is easy. Listing 12.2 shows the rules for our inputForm.

Listing 12.2: Rules for the inputForm.

start example
 <form-validation>     <formset>           <form name="inputForm">                <field property="userName"                        depends="minlength">                     <arg0 key="inputForm.userName"/>                     <arg1 key="${var:minlength}"                             name="minlength"                             resource="false"/>                     <var>                          <var-name>minlength</var-name>                          <var-value>5</var-value>                     </var>                </field>           </form>      </formset> </form-validation> 
end example



 < Day Day Up > 



Professional Jakarta Struts
Professional Jakarta Struts (Programmer to Programmer)
ISBN: 0764544373
EAN: 2147483647
Year: 2003
Pages: 183

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net