FirstCommonValidator.rar ValidateExample.java- /*
-
一直使用Struts 1,但没怎么详细看过它的Validator。
-
-
struts 1的validator是在 Apache commons validator的基础上扩展而来的。
-
-
下面的例子是摘自apache commons validator 中的例子,
-
(commons-validator-1.3.1-src.zip\commons-validator-1.3.1-src\src\*)
-
并在其基础上仅仅是做了点备注和测试。
-
-
lib:
-
commons-beanutils-1.8.2.jar
-
commons-beanutils-bean-collections-1.8.2.jar
-
commons-beanutils-core-1.8.2.jar
-
commons-digester-1.8.jar
-
commons-logging-1.1.1.jar
-
commons-validator-1.3.1.jar
-
*/
-
package org.apache.commons.validator.example;
-
-
import java.io.IOException;
-
import java.io.InputStream;
-
import java.text.MessageFormat;
-
import java.util.Iterator;
-
import java.util.Locale;
-
import java.util.ResourceBundle;
-
-
import org.apache.commons.validator.Arg;
-
import org.apache.commons.validator.Field;
-
import org.apache.commons.validator.Form;
-
import org.apache.commons.validator.Validator;
-
import org.apache.commons.validator.ValidatorAction;
-
import org.apache.commons.validator.ValidatorException;
-
import org.apache.commons.validator.ValidatorResources;
-
import org.apache.commons.validator.ValidatorResult;
-
import org.apache.commons.validator.ValidatorResults;
-
import org.xml.sax.SAXException;
-
-
public class ValidateExample extends Object {
-
-
private static ResourceBundle properties = ResourceBundle.getBundle("org.apache.commons.validator.example.applicationResources");
-
-
public static void main(String[] args) throws ValidatorException,
-
IOException, SAXException {
-
-
// 创建一个要验证的Bean
-
ValidateBean bean = new ValidateBean();
-
-
// Step 1. 加载设定文件
-
InputStream in = null;
-
ValidatorResources resources = null;
-
try {
-
in = ValidateExample.class.getResourceAsStream("validator-example.xml");
-
resources = new ValidatorResources(in);
-
} finally {
-
if (in != null) {
-
in.close();
-
}
-
}
-
-
// Step 2. 创建一个Validator, 并设置相关参数
-
Validator validator = new Validator(resources, "ValidateBean");
-
// 参数:要验证的JavaBean
-
validator.setParameter(Validator.BEAN_PARAM, bean);
-
// validator.setParameter(Validator.LOCALE_PARAM, java.util.Locale.CHINA); // 若未设置,则为系统默认
-
// validator.setParameter(Validator.VALIDATOR_ACTION_PARAM, new ValidatorAction()); // 自动设置
-
// validator.setParameter(Validator.FIELD_PARAM, new Field()); // 自动设置
-
// Locale locale = (Locale) validator.getParameterValue(Validator.LOCALE_PARAM);
-
-
/* 如何自定义Validator?
-
*
-
* 如果一个自定义验证方法的原型为
-
* boolean validateXXX(
-
* java.lang.Object,
-
* java.util.Locale,
-
* org.apache.commons.validator.ValidatorAction,
-
* org.apache.commons.validator.Field
-
* );
-
* 则 validator自动会将以下参数按类型传给相应的参数:
-
* Validator.BEAN_PARAM,
-
* Validator.LOCALE_PARAM,
-
* Validator.VALIDATOR_ACTION_PARAM,
-
* Validator.FIELD_PARAM
-
* (详见:包 org.apache.commons.validator 的Javadoc说明)
-
*/
-
-
// Step 3. 验证&&获取验证结果
-
-
// 第一次验证(应该只有 street2 能功过,因为未对它进行设定)
-
/* 结果输出:
-
=============第一次验证(全部为null,应该只有 street2, city 能功过,因为未对它们进行设定)
-
Validating:
-
{lastname=null, firstname=null, street1=null,
-
street2=null, city=null, state=null,
-
postalcode=null, age=null}
-
street1[required] (FAILED)
-
Error message will be: The 街道 field is required.
-
lastName[required] (FAILED)
-
Error message will be: The 姓氏 field is required.
-
postalCode[required] (FAILED)
-
Error message will be: The 邮编 field is required.
-
age[required] (FAILED)
-
Error message will be: The 年龄 field is required.
-
state[required] (FAILED)
-
Error message will be: The 省/州 field is required.
-
firstName[required] (FAILED)
-
Error message will be: The 名字 field is required.
-
验证失败!
-
*/
-
System.out.println("\n\n=============第一次验证(全部为null,"
-
+ "应该只有 street2, city 能功过,因为未对它们进行设定)");
-
ValidatorResults results = validator.validate();
-
printResults(bean, results, resources);
-
-
// 第二次验证
-
/* 结果输出:
-
=============第二次验证(通过required,但age不是数字字符串)
-
Validating:
-
{lastname=Tester, firstname=John, street1=1 Test Street,
-
street2=null, city=Testville, state=TE,
-
postalcode=12345, age=Too Old}
-
street1[required] (PASSED)
-
lastName[required] (PASSED)
-
postalCode[required] (PASSED)
-
age[int] (FAILED)
-
Error message will be: The 年龄 field is not an integer.
-
age[required] (PASSED)
-
state[required] (PASSED)
-
firstName[required] (PASSED)
-
验证失败!
-
*/
-
System.out.println("\n\n=============第二次验证(通过required,但age不是数字字符串)");
-
-
bean.setLastName("Tester");
-
bean.setFirstName("John");
-
bean.setStreet1("1 Test Street");
-
bean.setCity("Testville");
-
bean.setState("TE");
-
bean.setPostalCode("12345");
-
bean.setAge("Too Old");
-
-
results = validator.validate();
-
printResults(bean, results, resources);
-
-
// 第三次验证
-
/* 结果输出:
-
=============第三次验证(同第二次,但只返回验证错误信息,不返回验证成功信息)
-
Validating:
-
{lastname=Tester, firstname=John, street1=1 Test Street,
-
street2=null, city=Testville, state=TE,
-
postalcode=12345, age=Too Old}
-
age[int] (FAILED)
-
Error message will be: The 年龄 field is not an integer.
-
验证失败!
-
*/
-
System.out.println("\n\n=============第三次验证(同第二次,但只返回验证错误信息,不返回验证成功信息)");
-
-
// 设定只返回未通过的验证错误
-
validator.setOnlyReturnErrors(true);
-
results = validator.validate();
-
printResults(bean, results, resources);
-
-
// 第四次验证
-
/* 结果输出:
-
=============第四次验证(全部通过)
-
Validating:
-
{lastname=Tester, firstname=John, street1=1 Test Street,
-
street2=null, city=Testville, state=TE,
-
postalcode=12345, age=123}
-
street1[required] (PASSED)
-
lastName[required] (PASSED)
-
postalCode[required] (PASSED)
-
age[int] (PASSED)
-
age[required] (PASSED)
-
state[required] (PASSED)
-
firstName[required] (PASSED)
-
验证成功!
-
*/
-
-
System.out.println("\n\n=============第四次验证(全部通过)");
-
validator.setOnlyReturnErrors(false);
-
bean.setAge("123");
-
results = validator.validate();
-
printResults(bean, results, resources);
-
}
-
-
-
-
/**
-
* Dumps out the Bean in question and the results of validating it.
-
*/
-
public static void printResults(ValidateBean bean,
-
ValidatorResults results, ValidatorResources resources) {
-
-
boolean success = true;
-
-
System.out.println("Validating:");
-
System.out.println(bean);
-
-
// 循环验证结果中的所有字段
-
@SuppressWarnings("unchecked")
-
Iterator<String> propertyNames = results.getPropertyNames().iterator();
-
while (propertyNames.hasNext()) { // 对应validator-example.xml中
-
-
String propertyName = propertyNames.next();
-
-
// 对单个字段的检查结果(可能包含多个验证规则)
-
ValidatorResult result = results.getValidatorResult(propertyName);
-
-
// 循环当前字段的所有规则(ValidatorAction)及结果
-
@SuppressWarnings("unchecked")
-
Iterator<String> actionNames = result.getActions();
-
while (actionNames.hasNext()) {
-
String actName = actionNames.next();
-
-
ValidatorAction action = resources.getValidatorAction(actName);
-
-
-
// 打印 成功/失败
-
System.out.println(propertyName + "[" + actName + "] ("
-
+ (result.isValid(actName) ? "PASSED" : "FAILED") + ")");
-
-
// 打印 失败信息
-
if (!result.isValid(actName)) {
-
-
success = false;
-
-
// 获取 Message(可能包含多个参数)
-
String message = properties.getString(action.getMsg());
-
-
// 获取Message的参数
-
// JDK 的MessageFormat最多允许从0到9共10个参数。
-
Field field = result.getField();
-
Object[] args = new String[10];
-
for (int i = 0; i < args.length; i++) {
-
Arg arg = field.getArg(i);
-
if (arg == null) {
-
break;
-
}
-
String argKey = arg.getKey();
-
args[i] = properties.getString(argKey);
-
}
-
-
System.out.println(" Error message will be: "
-
+ MessageFormat.format(message, args));
-
}
-
}
-
}
-
-
if (success) {
-
System.out.println("验证成功!");
-
} else {
-
System.out.println("验证失败!");
-
}
-
}
-
}
- package org.apache.commons.validator.example;
-
-
public class ValidateBean extends Object {
-
-
String lastName, firstName, street1, street2, city, state, postalCode, age;
-
// getter && setter ...
-
-
public String toString() {
-
return "{lastname="
-
+ this.lastName
-
+ ", firstname="
-
+ this.firstName
-
+ ", street1="
-
+ this.street1
-
+ ",\n street2="
-
+ this.street2
-
+ ", "
-
+ "city="
-
+ this.city
-
+ ", state="
-
+ this.state
-
+ ",\n postalcode="
-
+ this.postalCode
-
+ ", age="
-
+ this.age
-
+ "}";
-
}
-
-
}
validator-example.xml
- <!DOCTYPE form-validation PUBLIC
-
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1//EN"
-
"">
-
-
<form-validation>
-
<global>
-
<!-- 追加各种Validator -->
-
<validator name="int"
-
classname="org.apache.commons.validator.TestTypeValidator"
-
method="validateInt"
-
methodParams="java.lang.Object,org.apache.commons.validator.Field"
-
msg="errors.int"/>
-
-
<validator name="required"
-
classname="org.apache.commons.validator.TestValidator"
-
method="validateRequired"
-
methodParams="java.lang.Object,org.apache.commons.validator.Field"
-
msg="errors.required"/>
-
</global>
-
<formset>
-
<!-- 定义验证表单的名称 -->
-
<form name="ValidateBean">
-
<!-- 需要验证的属性及验证规则 -->
-
<field property="firstName" depends="required">
-
<arg key="nameForm.firstname.displayname"/> <!-- 消息的参数 -->
-
</field>
-
<field property="lastName" depends="required">
-
<arg key="nameForm.lastname.displayname"/>
-
</field>
-
<field property="street1" depends="required">
-
<arg key="nameForm.street1.displayname"/>
-
</field>
-
<field property="state" depends="required">
-
<arg key="nameForm.city.displayname"/>
-
</field>
-
<field property="state" depends="required">
-
<arg key="nameForm.state.displayname"/>
-
</field>
-
<field property="postalCode" depends="required">
-
<arg key="nameForm.postalCode.displayname"/>
-
</field>
-
<field property="age" depends="required,int">
-
<arg key="nameForm.age.displayname"/>
-
</field>
-
-
</form>
-
</formset>
-
</form-validation>
TestTypeValidator.java
- package org.apache.commons.validator;
-
-
import java.util.*;
-
-
import org.apache.commons.validator.util.ValidatorUtils;
- public class TestTypeValidator {
-
public static Byte validateByte(Object bean, Field field) { ... }
-
public static Byte validateByte(Object bean, Field field, Locale locale) { ... }
-
public static Short validateShort(Object bean, Field field) { ... }
-
public static Short validateShort(Object bean, Field field, Locale locale) { ... }
-
public static Integer validateInt(Object bean, Field field){ ... }
-
public static Integer validateInt(Object bean, Field field, Locale locale){ ... }
-
public static Long validateLong(Object bean, Field field){ ... }
-
public static Long validateLong(Object bean, Field field, Locale locale) { ... }
-
public static Float validateFloat(Object bean, Field field) { ... }
-
public static Float validateFloat(Object bean, Field field, Locale locale) { ... }
-
public static Double validateDouble(Object bean, Field field) { ... }
-
public static Double validateDouble(Object bean, Field field, Locale locale) { ... }
-
public static Date validateDate(Object bean, Field field, Locale locale) { ... }
-
public static Date validateDate(Object bean, Field field) { ... }
-
}
TestValidator.java- package org.apache.commons.validator;
-
-
import org.apache.commons.validator.util.ValidatorUtils;
-
-
public class TestValidator {
-
public static boolean validateRaiseException(final Object bean, final Field field) throws Exception { ... }
-
public static boolean validateRequired(Object bean, Field field) { ... }
-
public static boolean validateByte(Object bean, Field field) { ... }
-
public static boolean validateShort(Object bean, Field field) { ... }
-
public static boolean validateInt(Object bean, Field field) { ... }
-
public static boolean validatePositive(Object bean , Field field) { ... }
-
public static boolean validateLong(Object bean, Field field) { ... }
-
public static boolean validateFloat(Object bean, Field field) { ... }
-
public static boolean validateDouble(Object bean, Field field) { ... }
-
public static boolean validateEmail(Object bean, Field field) { ... }
-
public static boolean validateRequiredIf(Object bean, Field field, Validator validator) { ... }
-
}
阅读(4171) | 评论(0) | 转发(0) |