Hibernate Validation目前最新的稳定版本是:5.1.3. 下载地址
官网地址
官方英文使用手册
官方中文使用手册地址(中文版目前最新的是4.3版本)
具体使用方法请查看上面的官方使用手册地址,每个注解对应的含义在官方手册2.4章节有详细介绍,内容太多我就不贴过来了.下面直接上最常用情况(实体类校验)的示例代码.
一、依赖包
J2SE环境下除了需要引入Hibernate Validation包外,还需要额外引入两个实现表达式语言的包.J2EE环境如果容器提供不需要再引入.下面是J2SE环境下的依赖包:
org.hibernate
hibernate-validator
5.1.3.Final
javax.el
javax.el-api
2.2.4
org.glassfish.web
javax.el
2.2.4
/**
* 校验工具类
*/
public class ValidationUtils {
private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
public static ValidationResult validateEntity(T obj){
ValidationResult result = new ValidationResult();
Set> set = validator.validate(obj,Default.class);
if( CollectionUtils.isNotEmpty(set) ){
result.setHasErrors(true);
Map errorMsg = new HashMap();
for(ConstraintViolation cv : set){
errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());
}
result.setErrorMsg(errorMsg);
}
return result;
}
public static ValidationResult validateProperty(T obj,String propertyName){
ValidationResult result = new ValidationResult();
Set> set = validator.validateProperty(obj,propertyName,Default.class);
if( CollectionUtils.isNotEmpty(set) ){
result.setHasErrors(true);
Map errorMsg = new HashMap();
for(ConstraintViolation cv : set){
errorMsg.put(propertyName, cv.getMessage());
}
result.setErrorMsg(errorMsg);
}
return result;
}
}
/**
* 校验结果
*/
public class ValidationResult {
//校验结果是否有错
private boolean hasErrors;
//校验错误信息
private Map errorMsg;
public boolean isHasErrors() {
return hasErrors;
}
public void setHasErrors(boolean hasErrors) {
this.hasErrors = hasErrors;
}
public Map getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(Map errorMsg) {
this.errorMsg = errorMsg;
}
@Override
public String toString() {
return "ValidationResult [hasErrors=" + hasErrors + ", errorMsg="
+ errorMsg + "]";
}
}
public class SimpleEntity {
@NotBlank(message="名字不能为空或者空串")
@Length(min=2,max=10,message="名字必须由2~10个字组成")
private String name;
@Past(message="时间不能晚于当前时间")
private Date date;
@Email(message="邮箱格式不正确")
private String email;
@Pattern(regexp="(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{5,10}",message="密码必须是5~10位数字和字母的组合")
private String password;
@AssertTrue(message="字段必须为真")
private boolean valid;
//get set方法省略,自己添加
}
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordValidator.class)
@Documented
public @interface Password {
String message() default "{密码必须是5~10位数字和字母组合}";
Class>[] groups() default {};
Class extends Payload>[] payload() default {};
}
/**
* 自定义密码校验类
*/
public class PasswordValidator implements ConstraintValidator {
//5~10位的数字与字母组合
private static Pattern pattern = Pattern.compile("(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{5,10}");
public void initialize(Password constraintAnnotation) {
//do nothing
}
public boolean isValid(String value, ConstraintValidatorContext context) {
if( value==null ){
return false;
}
Matcher m = pattern.matcher(value);
return m.matches();
}
}
三、被校验实体
public class ExtendEntity {
@Password
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public class ValidationUtilsTest extends TestCase{
public void validateSimpleEntity() {
SimpleEntity se = new SimpleEntity();
se.setDate(new Date());
se.setEmail("123");
se.setName("123");
se.setPassword("123");
se.setValid(false);
ValidationResult result = ValidationUtils.validateEntity(se);
System.out.println("--------------------------");
System.out.println(result);
Assert.assertTrue(result.isHasErrors());
}
public void validateSimpleProperty() {
SimpleEntity se = new SimpleEntity();
ValidationResult result = ValidationUtils.validateProperty(se,"name");
System.out.println("--------------------------");
System.out.println(result);
Assert.assertTrue(result.isHasErrors());
}
public void validateExtendEntity() {
ExtendEntity ee = new ExtendEntity();
ee.setPassword("212");
ValidationResult result = ValidationUtils.validateEntity(ee);
System.out.println("--------------------------");
System.out.println(result);
Assert.assertTrue(result.isHasErrors());
}
}
代码在JDK1.8下测试通过. 完整代码可查看我的Github仓库: https://github.com/wdmcygah/research-J2SE