Chapter 7: Tiles


Adding Validator to the Mini HR Application

Now that you've seen the benefits of using the Validator framework and how it works, you are ready to revisit the Mini HR application and replace the hard-coded validation logic with Validator. Following is the list of steps involved in adding the Validator to the Mini HR application:

  1. Change SearchForm to extend ValidatorForm.

  2. Create a validation.xml file.

  3. Add the Validator plugin to the struts-config.xml file.

  4. Add Validation error messages to the MessageResources.properties file.

  5. Recompile, repackage, and run the updated application.

The following sections walk through each step of the process in detail.

Change SearchForm to Extend ValidatorForm

The first step in converting the Mini HR application to use Validator is to change SearchForm to extend Validator's ValidatorForm class instead of extending Struts' basic ActionForm class. Recall that ValidatorForm extends ActionForm and provides an implementation for its reset() and validate( ) methods that hook into the Validator framework; thus, those methods should be removed from the SearchForm class. Additionally, the isValidSsNum( ) method should be removed from the SearchForm class because its functionality is being replaced by Validator as well.

Following is the updated SearchForm.java file:

package com.jamesholmes.minihr;     import java.util.List; import org.apache.struts.validator.ValidatorForm;     public class SearchForm extends ValidatorForm {   private String name = null;   private String ssNum = null;   private List results = null;       public void setName(String name) {     this.name = name;   }   public String getName() {     return name;   }       public void setSsNum(String ssNum) {     this.ssNum = ssNum;   }       public String getSsNum() {     return ssNum;   }       public void setResults(List results) {     this.results = results;   }       public List getResults() {     return results;   } }

Notice that this file no longer has the reset( ), validate( ), and validateSsNum( ) methods and that the class been updated to extend ValidatorForm.

Create a validation.xml File

After removing the hard-coded validation logic from SearchForm, you must create a validation.xml file. This file will inform Validator which validations from the validator-rules.xml file should be applied to SearchForm. Following is a basic validation.xml file that validates that social security numbers have the proper format if entered:

<!DOCTYPE form-validation PUBLIC           "-//Apache Software Foundation//DTD Commons             Validator Rules Configuration 1.3.0//EN"           "http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd">     <form-validation>   <formset>     <form name="searchForm">       <field property="ssNum" depends="mask">         <arg position="0" key="label.search.ssNum"/>         <var>           <var-name>mask</var-name>           <var-value>^\d{3}-\d{2}-\d{4}$</var-value>         </var>       </field>     </form>   </formset> </form-validation>

Notice that this file does not contain any validation definitions to ensure that either a name or a social security number was entered, the way the original hard-coded logic did. This is because such logic is complicated to implement with Validator and thus should be implemented using Struts' basic validation mechanism.

Add the Validator Plugin to the struts-config.xml File

After setting up Validator's configuration file, the following snippet must be added to the Struts configuration file to cause Struts to load the Validator plugin:

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

Notice that each of the configuration files is specified with the set-property tag. The following snippet lists the updated Struts configuration file for Mini HR in its entirety:

<!DOCTYPE struts-config PUBLIC   "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"   "http://struts.apache.org/dtds/struts-config_1_3.dtd">     <struts-config>       <!-- Form Beans Configuration -->   <form-beans>     <form-bean name="searchForm"                type="com.jamesholmes.minihr.SearchForm"/>   </form-beans>       <!-- Global Forwards Configuration -->   <global-forwards>     <forward name="search" path="/search.jsp"/>   </global-forwards>       <!-- Action Mappings Configuration -->   <action-mappings>     <action path="/search"             type="com.jamesholmes.minihr.SearchAction"             name="searchForm"             scope="request"             validate="true"             input="/search.jsp">     </action>   </action-mappings>       <!-- Message Resources Configuration -->   <message-resources     parameter="com.jamesholmes.minihr.MessageResources"/>       <!-- Validator Configuration -->   <plug-in className="org.apache.struts.validator.ValidatorPlugIn">     <set-property property="pathnames"                   value="/org/apache/struts/validator/validator-rules.xml,                          /WEB-INF/validation.xml"/>   </plug-in>     </struts-config> 

Add Validation Error Messages to the MessageResources.properties File

Recall from earlier in this chapter that each validation routine defined in the validator-rules. xml file declares a key for an error message in Struts' resource bundle file: MessageResources.properties. At run time, Validator uses the keys to look up error messages to return when validations fail. Because you are using the mask validation defined in the validator-rules. xml file, you must add the following error message for its declared key to the MessageResources.properties file:

errors.invalid={0} is not valid

The following code shows the updated MessageResources.properties file in its entirety:

# Label Resources label.search.name=Name label.search.ssNum=Social Security Number     # Error Resources error.search.criteria.missing=Search Criteria Missing error.search.ssNum.invalid=Invalid Social Security Number errors.header=<font color="red"><cTypeface:Bold>Validation Error(s)</b></font><ul> errors.footer=</ul><hr width="100%" size="1" noshade="true"> errors.prefix=<li> errors.suffix=</li>     errors.invalid={0} is not valid 

Compile, Package, and Run the Updated Application

Because you removed the reset( ), validate( ), and validateSsNum( ) methods from SearchForm and changed it to extend ValidatorForm instead of ActionForm, you need to recompile and repackage the Mini HR application before you run it. Assuming that you've made modifications to the original Mini HR application and it was set up in the c:\java\ MiniHR directory (as described in Chapter 2), you can run the build.bat batch file or the build.xml Ant script file to recompile the application.

After recompiling Mini HR, you need to repackage it using the following command line:

jar cf MiniHR.war *

This command should also be run from the directory where you have set up the Mini HR application (e.g., c:\java\MiniHR).

Similar to the way you ran Mini HR the first time, you now need to place the new MiniHR.war file that you just created into Tomcat's webapps directory, delete the webapps/MiniHR directory, and start Tomcat. As before, to access the Mini HR application, point your browser to http://localhost:8080/MiniHR/. Once you have the updated Mini HR running, try entering valid and invalid social security numbers. As you will see, they are now verified using the new Validator code.



Struts. The Complete Reference
Struts: The Complete Reference, 2nd Edition
ISBN: 0072263865
EAN: 2147483647
Year: 2004
Pages: 165
Authors: James Holmes

Similar book on Amazon
Struts 2 in Action
Struts 2 in Action
Murach's Java Servlets and JSP, 2nd Edition
Murach's Java Servlets and JSP, 2nd Edition
Jakarta Struts For Dummies
Jakarta Struts For Dummies
Head First Servlets and JSP: Passing the Sun Certified Web Component Developer Exam
Head First Servlets and JSP: Passing the Sun Certified Web Component Developer Exam

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