Chinaunix首页 | 论坛 | 博客
  • 博客访问: 530274
  • 博文数量: 135
  • 博客积分: 3568
  • 博客等级: 中校
  • 技术积分: 1942
  • 用 户 组: 普通用户
  • 注册时间: 2006-10-19 17:52
文章分类

全部博文(135)

文章存档

2012年(29)

2011年(41)

2010年(26)

2009年(12)

2008年(9)

2007年(12)

2006年(6)

分类: Java

2011-03-18 11:21:11

 FirstCommonValidator.rar  

ValidateExample.java
  1. /*
  2. 一直使用Struts 1,但没怎么详细看过它的Validator。

  3. struts 1的validator是在 Apache commons validator的基础上扩展而来的。

  4. 下面的例子是摘自apache commons validator 中的例子,
  5. (commons-validator-1.3.1-src.zip\commons-validator-1.3.1-src\src\*)
  6. 并在其基础上仅仅是做了点备注和测试。

  7. lib:
  8. commons-beanutils-1.8.2.jar
  9. commons-beanutils-bean-collections-1.8.2.jar
  10. commons-beanutils-core-1.8.2.jar
  11. commons-digester-1.8.jar
  12. commons-logging-1.1.1.jar
  13. commons-validator-1.3.1.jar
  14.  */
  15. package org.apache.commons.validator.example;

  16. import java.io.IOException;
  17. import java.io.InputStream;
  18. import java.text.MessageFormat;
  19. import java.util.Iterator;
  20. import java.util.Locale;
  21. import java.util.ResourceBundle;

  22. import org.apache.commons.validator.Arg;
  23. import org.apache.commons.validator.Field;
  24. import org.apache.commons.validator.Form;
  25. import org.apache.commons.validator.Validator;
  26. import org.apache.commons.validator.ValidatorAction;
  27. import org.apache.commons.validator.ValidatorException;
  28. import org.apache.commons.validator.ValidatorResources;
  29. import org.apache.commons.validator.ValidatorResult;
  30. import org.apache.commons.validator.ValidatorResults;
  31. import org.xml.sax.SAXException;

  32. public class ValidateExample extends Object {

  33.     private static ResourceBundle properties = ResourceBundle.getBundle("org.apache.commons.validator.example.applicationResources");

  34.     public static void main(String[] args) throws ValidatorException,
  35.             IOException, SAXException {

  36.         // 创建一个要验证的Bean
  37.         ValidateBean bean = new ValidateBean();

  38.         // Step 1. 加载设定文件
  39.         InputStream in = null;
  40.         ValidatorResources resources = null;
  41.         try {
  42.             in = ValidateExample.class.getResourceAsStream("validator-example.xml");
  43.             resources = new ValidatorResources(in);
  44.         } finally {
  45.             if (in != null) {
  46.                 in.close();
  47.             }
  48.         }

  49.         // Step 2. 创建一个Validator, 并设置相关参数
  50.         Validator validator = new Validator(resources, "ValidateBean");
  51.         // 参数:要验证的JavaBean
  52.         validator.setParameter(Validator.BEAN_PARAM, bean);
  53.         // validator.setParameter(Validator.LOCALE_PARAM, java.util.Locale.CHINA); // 若未设置,则为系统默认
  54.         // validator.setParameter(Validator.VALIDATOR_ACTION_PARAM, new ValidatorAction()); // 自动设置
  55.         // validator.setParameter(Validator.FIELD_PARAM, new Field()); // 自动设置
  56.         // Locale locale = (Locale) validator.getParameterValue(Validator.LOCALE_PARAM);

  57.         /* 如何自定义Validator?
  58.          *
  59.          * 如果一个自定义验证方法的原型为
  60.          * boolean validateXXX(
  61.          * java.lang.Object,
  62.          * java.util.Locale,
  63.          * org.apache.commons.validator.ValidatorAction,
  64.          * org.apache.commons.validator.Field
  65.          * );
  66.          * 则 validator自动会将以下参数按类型传给相应的参数:
  67.          * Validator.BEAN_PARAM,
  68.          * Validator.LOCALE_PARAM,
  69.          * Validator.VALIDATOR_ACTION_PARAM,
  70.          * Validator.FIELD_PARAM
  71.          * (详见:包 org.apache.commons.validator 的Javadoc说明)
  72.          */

  73.         // Step 3. 验证&&获取验证结果

  74.         // 第一次验证(应该只有 street2 能功过,因为未对它进行设定)
  75.         /* 结果输出:
  76. =============第一次验证(全部为null,应该只有 street2, city 能功过,因为未对它们进行设定)
  77. Validating:
  78. {lastname=null, firstname=null, street1=null,
  79.  street2=null, city=null, state=null,
  80.  postalcode=null, age=null}
  81. street1[required] (FAILED)
  82.      Error message will be: The 街道 field is required.
  83. lastName[required] (FAILED)
  84.      Error message will be: The 姓氏 field is required.
  85. postalCode[required] (FAILED)
  86.      Error message will be: The 邮编 field is required.
  87. age[required] (FAILED)
  88.      Error message will be: The 年龄 field is required.
  89. state[required] (FAILED)
  90.      Error message will be: The 省/州 field is required.
  91. firstName[required] (FAILED)
  92.      Error message will be: The 名字 field is required.
  93. 验证失败!
  94.          */
  95.         System.out.println("\n\n=============第一次验证(全部为null,"
  96.                 + "应该只有 street2, city 能功过,因为未对它们进行设定)");
  97.         ValidatorResults results = validator.validate();
  98.         printResults(bean, results, resources);

  99.         // 第二次验证
  100.         /* 结果输出:
  101. =============第二次验证(通过required,但age不是数字字符串)
  102. Validating:
  103. {lastname=Tester, firstname=John, street1=1 Test Street,
  104.  street2=null, city=Testville, state=TE,
  105.  postalcode=12345, age=Too Old}
  106. street1[required] (PASSED)
  107. lastName[required] (PASSED)
  108. postalCode[required] (PASSED)
  109. age[int] (FAILED)
  110.      Error message will be: The 年龄 field is not an integer.
  111. age[required] (PASSED)
  112. state[required] (PASSED)
  113. firstName[required] (PASSED)
  114. 验证失败!
  115.          */
  116.         System.out.println("\n\n=============第二次验证(通过required,但age不是数字字符串)");

  117.         bean.setLastName("Tester");
  118.         bean.setFirstName("John");
  119.         bean.setStreet1("1 Test Street");
  120.         bean.setCity("Testville");
  121.         bean.setState("TE");
  122.         bean.setPostalCode("12345");
  123.         bean.setAge("Too Old");

  124.         results = validator.validate();
  125.         printResults(bean, results, resources);

  126.         // 第三次验证
  127.         /* 结果输出:
  128. =============第三次验证(同第二次,但只返回验证错误信息,不返回验证成功信息)
  129. Validating:
  130. {lastname=Tester, firstname=John, street1=1 Test Street,
  131.  street2=null, city=Testville, state=TE,
  132.  postalcode=12345, age=Too Old}
  133. age[int] (FAILED)
  134.      Error message will be: The 年龄 field is not an integer.
  135. 验证失败!
  136.          */
  137.         System.out.println("\n\n=============第三次验证(同第二次,但只返回验证错误信息,不返回验证成功信息)");

  138.         // 设定只返回未通过的验证错误
  139.         validator.setOnlyReturnErrors(true);
  140.         results = validator.validate();
  141.         printResults(bean, results, resources);

  142.         // 第四次验证
  143.         /* 结果输出:
  144. =============第四次验证(全部通过)
  145. Validating:
  146. {lastname=Tester, firstname=John, street1=1 Test Street,
  147.  street2=null, city=Testville, state=TE,
  148.  postalcode=12345, age=123}
  149. street1[required] (PASSED)
  150. lastName[required] (PASSED)
  151. postalCode[required] (PASSED)
  152. age[int] (PASSED)
  153. age[required] (PASSED)
  154. state[required] (PASSED)
  155. firstName[required] (PASSED)
  156. 验证成功!
  157.          */
  158.          
  159.         System.out.println("\n\n=============第四次验证(全部通过)");
  160.         validator.setOnlyReturnErrors(false);
  161.         bean.setAge("123");
  162.         results = validator.validate();
  163.         printResults(bean, results, resources);
  164.     }
  165.     
  166.     
  167.     
  168.     /**
  169.      * Dumps out the Bean in question and the results of validating it.
  170.      */
  171.     public static void printResults(ValidateBean bean,
  172.             ValidatorResults results, ValidatorResources resources) {

  173.         boolean success = true;

  174.         System.out.println("Validating:");
  175.         System.out.println(bean);

  176.         // 循环验证结果中的所有字段
  177.         @SuppressWarnings("unchecked")
  178.         Iterator<String> propertyNames = results.getPropertyNames().iterator();
  179.         while (propertyNames.hasNext()) { // 对应validator-example.xml中

  180.             String propertyName = propertyNames.next();

  181.             // 对单个字段的检查结果(可能包含多个验证规则)
  182.             ValidatorResult result = results.getValidatorResult(propertyName);

  183.             // 循环当前字段的所有规则(ValidatorAction)及结果
  184.             @SuppressWarnings("unchecked")
  185.             Iterator<String> actionNames = result.getActions();
  186.             while (actionNames.hasNext()) {
  187.                 String actName = actionNames.next();
  188.                 
  189.                 ValidatorAction action = resources.getValidatorAction(actName);
  190.                 

  191.                 // 打印 成功/失败
  192.                 System.out.println(propertyName + "[" + actName + "] ("
  193.                         + (result.isValid(actName) ? "PASSED" : "FAILED") + ")");

  194.                 // 打印 失败信息
  195.                 if (!result.isValid(actName)) {
  196.                     
  197.                     success = false;

  198.                     // 获取 Message(可能包含多个参数)
  199.                     String message = properties.getString(action.getMsg());

  200.                     // 获取Message的参数
  201.                     // JDK 的MessageFormat最多允许从0到9共10个参数。
  202.                     Field field = result.getField();
  203.                     Object[] args = new String[10];
  204.                     for (int i = 0; i < args.length; i++) {
  205.                         Arg arg = field.getArg(i);
  206.                         if (arg == null) {
  207.                             break;
  208.                         }
  209.                         String argKey = arg.getKey();
  210.                         args[i] = properties.getString(argKey);
  211.                     }
  212.                     
  213.                     System.out.println(" Error message will be: "
  214.                             + MessageFormat.format(message, args));
  215.                 }
  216.             }
  217.         }
  218.         
  219.         if (success) {
  220.             System.out.println("验证成功!");
  221.         } else {
  222.             System.out.println("验证失败!");
  223.         }
  224.     }
  225. }

  1. package org.apache.commons.validator.example;

  2. public class ValidateBean extends Object {

  3.     String lastName, firstName, street1, street2, city, state, postalCode, age;

  4.     // getter && setter ...

  5.     public String toString() {
  6.         return "{lastname="
  7.             + this.lastName
  8.             + ", firstname="
  9.             + this.firstName
  10.             + ", street1="
  11.             + this.street1
  12.             + ",\n street2="
  13.             + this.street2
  14.             + ", "
  15.             + "city="
  16.             + this.city
  17.             + ", state="
  18.             + this.state
  19.             + ",\n postalcode="
  20.             + this.postalCode
  21.             + ", age="
  22.             + this.age
  23.             + "}";
  24.     }

  25. }
validator-example.xml
  1. <!DOCTYPE form-validation PUBLIC
  2.      "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1//EN"
  3.      "">
  4.      
  5. <form-validation>
  6.    <global>
  7.       <!-- 追加各种Validator -->
  8.       <validator name="int"
  9.                  classname="org.apache.commons.validator.TestTypeValidator"
  10.                  method="validateInt"
  11.                  methodParams="java.lang.Object,org.apache.commons.validator.Field"
  12.                  msg="errors.int"/>

  13.       <validator name="required"
  14.                  classname="org.apache.commons.validator.TestValidator"
  15.                  method="validateRequired"
  16.                  methodParams="java.lang.Object,org.apache.commons.validator.Field"
  17.                  msg="errors.required"/>
  18.    </global>
  19.    <formset>
  20.       <!-- 定义验证表单的名称 -->
  21.       <form name="ValidateBean">
  22.          <!-- 需要验证的属性及验证规则 -->
  23.          <field property="firstName" depends="required">
  24.               <arg key="nameForm.firstname.displayname"/> <!-- 消息的参数 -->
  25.          </field>
  26.          <field property="lastName" depends="required">
  27.               <arg key="nameForm.lastname.displayname"/>
  28.          </field>
  29.          <field property="street1" depends="required">
  30.               <arg key="nameForm.street1.displayname"/>
  31.          </field>
  32.          <field property="state" depends="required">
  33.               <arg key="nameForm.city.displayname"/>
  34.          </field>
  35.          <field property="state" depends="required">
  36.               <arg key="nameForm.state.displayname"/>
  37.          </field>
  38.          <field property="postalCode" depends="required">
  39.               <arg key="nameForm.postalCode.displayname"/>
  40.          </field>
  41.          <field property="age" depends="required,int">
  42.               <arg key="nameForm.age.displayname"/>
  43.          </field>

  44.       </form>
  45.    </formset>
  46. </form-validation>
TestTypeValidator.java
  1. package org.apache.commons.validator;

  2. import java.util.*;

  3. import org.apache.commons.validator.util.ValidatorUtils;

  4. public class TestTypeValidator {
  5.   public static Byte validateByte(Object bean, Field field) { ... }
  6.   public static Byte validateByte(Object bean, Field field, Locale locale) { ... }
  7.   public static Short validateShort(Object bean, Field field) { ... }
  8.   public static Short validateShort(Object bean, Field field, Locale locale) { ... }
  9.   public static Integer validateInt(Object bean, Field field){ ... }
  10.   public static Integer validateInt(Object bean, Field field, Locale locale){ ... }
  11.   public static Long validateLong(Object bean, Field field){ ... }
  12.   public static Long validateLong(Object bean, Field field, Locale locale) { ... }
  13.   public static Float validateFloat(Object bean, Field field) { ... }
  14.   public static Float validateFloat(Object bean, Field field, Locale locale) { ... }
  15.   public static Double validateDouble(Object bean, Field field) { ... }
  16.   public static Double validateDouble(Object bean, Field field, Locale locale) { ... }
  17.   public static Date validateDate(Object bean, Field field, Locale locale) { ... }
  18.   public static Date validateDate(Object bean, Field field) { ... }
  19. }

TestValidator.java
  1. package org.apache.commons.validator;

  2. import org.apache.commons.validator.util.ValidatorUtils;

  3. public class TestValidator {
  4.   public static boolean validateRaiseException(final Object bean, final Field field) throws Exception { ... }
  5.   public static boolean validateRequired(Object bean, Field field) { ... }
  6.   public static boolean validateByte(Object bean, Field field) { ... }
  7.   public static boolean validateShort(Object bean, Field field) { ... }
  8.   public static boolean validateInt(Object bean, Field field) { ... }
  9.   public static boolean validatePositive(Object bean , Field field) { ... }
  10.   public static boolean validateLong(Object bean, Field field) { ... }
  11.   public static boolean validateFloat(Object bean, Field field) { ... }
  12.   public static boolean validateDouble(Object bean, Field field) { ... }
  13.   public static boolean validateEmail(Object bean, Field field) { ... }
  14.   public static boolean validateRequiredIf(Object bean, Field field, Validator validator) { ... }
  15. }


阅读(4171) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~