最近接触到了这个东西,绕有兴趣,稍稍学习了一下。
啥也不说,现来练上一把,先来搭建我们的开发环境吧:
要用到的三方类库依赖:spring,spring-modules-validation,spring-test ,junit
我用的是maven,如果你用别的构建也可以,把以上类加到eclipse 的buildPath里面来就行了。
首先执行:
mvn archetype:generate |
生成了目录
然后编辑POM如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.yajun</groupId> <artifactId>valangDemo</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>valangDemo</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.0</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springmodules</groupId> <artifactId>spring-modules-validation</artifactId> <version>0.5</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>2.5</version> <scope>compile</scope> </dependency> </dependencies> </project>
然后执行
mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true |
导入eclipse。
创建 src/main/resources 源文件文件夹
创建valang.xml 如下:
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd"> <beans> <bean id="userValidator" class="com.yajun.validate.UserValidate"> <property name="valang"> <value> <![CDATA[ { name : ? is not null and ? has text and match('^abc.*$',?) is true : 'Name is empty or too long.'} { age : ? between 0 and 60 : 'Age should between 0 and 60.'} { birthday : ? is null or ? >[20000101] : 'Birthday should be after 2000-01-01.'} ]]> </value> </property> <property name="dateParsers"> <map> <entry key="^\\d{8}$" value="yyyyMMdd" /> </map> </property> <property name="addressValidator" ref="addressValidator" /> </bean> <bean id="addressValidator" class="org.springmodules.validation.valang.ValangValidator"> <property name="valang"> <value> <![CDATA[ { state : ? is not null and ? has text and length(?)<=50 : 'state is empty or too long.'} { town : ? is not null and ? has text and length(?)<=50 : 'town is empty or too long.'} { street : ? is not null and ? has text and length(?)<=50 : 'street is empty or too long.'} ]]> </value> </property> </bean> </beans>
创建一个简单的JAVA类:
package com.yajun.dataobject; import java.util.Date; /** * 简单用户对象 * * @author yajun * */ public class User { private String name; // 姓名 检验字符串格式校验 private Date birthday; // 生日 检验时间格式校验 private Address address; // 地址 检验复杂类型校验 private int age; // 年龄 检验数字类型校验 public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
创建复杂地址对象:
package com.yajun.dataobject; /** * 地址信息 * * @author yajun * */ public class Address { private String state; // 州 private String town; // 镇 private String street; // 街道 public String getState() { return state; } public void setState(String state) { this.state = state; } public String getTown() { return town; } public void setTown(String town) { this.town = town; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } }
创建自定义的validate类:
package com.yajun.validate; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import org.springmodules.validation.valang.ValangValidator; import com.yajun.dataobject.Address; import com.yajun.dataobject.User; /** * 自定义用户校验器 * * @author yajun * */ public class UserValidate extends ValangValidator { private Validator addressValidator; public void setAddressValidator(Validator addressValidator) { this.addressValidator = addressValidator; } public void validate(Object target, Errors errors) { super.validate(target, errors); Address address = ((User) target).getAddress(); // address 为 null 时,不进行进一步的验证。 if (null != address) { // 注意与 popNestedPath 成对使用 errors.pushNestedPath("address"); // 验证 address addressValidator.validate(address, errors); errors.popNestedPath(); } } }
再整个单元测试跑一下吧:
package com.yajun; import java.util.List; import org.springframework.test.AbstractDependencyInjectionSpringContextTests; import org.springframework.validation.BindException; import org.springframework.validation.ObjectError; import org.springframework.validation.Validator; import com.yajun.dataobject.Address; import com.yajun.dataobject.User; /** * Unit test for simple App. */ public class UserValidatorTest extends AbstractDependencyInjectionSpringContextTests { private Validator userValidator; public UserValidatorTest() { super(); // 缺省是AUTOWIRE_BY_TYPE,当Bean文件有2个以上的同类型 // Bean定义时就应该采用AUTOWIRE_BY_NAME方式。 setAutowireMode(AUTOWIRE_BY_NAME); } protected String[] getConfigLocations() { // 指明配置文件的位置 return new String[] { "valang.xml" }; } // 基类调用该方法完成依赖注入(DI) public void setUserValidator(Validator userValidator) { this.userValidator = userValidator; } public void testEmptyObject() { User user = new User(); user.setName(""); Address address = new Address(); address.setState("中国"); user.setAddress(address); BindException errors = new BindException(user, "target"); userValidator.validate(user, errors); List<ObjectError> errorList = errors.getAllErrors(); for (ObjectError o : errorList) { System.out.println(o.getDefaultMessage()); } } }
跑成功了吧。