Home arrow Java arrow Page 9 - Validator
JAVA

Validator


The Struts framework features a built-in database for performing data validations on incoming form data. Its simple interface means that developers can focus on writing validation code; additionally, you can plug your own custom routines into Validator. This article shows you how. It is taken from chapter six of the book The Complete Reference Struts, written by James Holmes (McGraw-Hill/Osborne, 2004; ISBN: 0072231319).

Author Info:
By: McGraw-Hill/Osborne
Rating: 4 stars4 stars4 stars4 stars4 stars / 29
September 22, 2005
TABLE OF CONTENTS:
  1. · Validator
  2. · Validator Overview
  3. · Included Validations
  4. · Creating Form Beans
  5. · Configuring validation.xml
  6. · Enabling Client-Side Validations
  7. · Adding a New Validation Rule
  8. · Internationalizing Validations
  9. · Create a validation.xml File

print this article
SEARCH DEVARTICLES

Validator - Create a validation.xml File
(Page 9 of 9 )

After removing the hard-coded validation logic from SearchForm and adding a validator-rules.xml file, 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.0//EN"
          "http://jakarta.apache.org/ commons/dtds/validator_1_0.dtd">
<form-validation>
  <formset>
    <form name="searchForm">
     
<field property="ssNum" depends="mask">
        <arg0 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 files, 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="/WEB-INF/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.1//EN"
  "http://jakarta.apache.org/struts/dtds/struts-config_1_1.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. ApplicationResources"/>
  <!-- valalidator Configuration -->
 
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
    <set-property property="pathnames"
                  value="/WEB-INF/validator-rules.xml,
                         /WEB-INF/validation.xml"/>
  </plug-in>
</struts-config>

Add Validation Error Messages to the ApplicationResources.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: ApplicationResources.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 ApplicationResources.propertiesfile:

errors.invalid=<li>{0} is not valid</li>

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

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

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), the following command line will recompile the application:

javac -classpath WEB-INF\lib\commons-beanutils.jar;
                 WEB-INF\lib\commons-collections.jar;
                 WEB-INF\lib\commons-lang.jar;
                 WEB-INF\lib\commons-logging.jar;
                 WEB-INF\lib\commons-validator.jar;
                 WEB-INF\lib\digester.jar;
                 WEB-INF\lib\fileupload.jar;
                 WEB-INF\lib\jakarta-oro.jar;
                
WEB-INF\lib\struts.jar;
                
C:\java\jakarta-tomcat-4.1.27\common\lib\servlet.jar
                  
WEB-INF\src\com\ jamesholmes\minihr\*.java
                  
-d WEB-INF\classes

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 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.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials