今天我们来谈谈后台验证Validation
后台开发需要对对象的传进来的参数进行校验,有专门的校验工具,validation bean 是基于JSR-303标准开发出来的,使用注解方式实现,及其方便,但是这只是一个接口,没有具体实现
Hibernate Validator是一个hibernate独立的包,可以直接引用,他实现了validation bean同时有做了扩展,比较强大。
要在pom.xml里面添加依赖:
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
@Pattern(regexp = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$", message = "邮箱格式不正确")
private String to;
当然我们也可以封装成一个帮助类:
package com.alibaba.banff.web.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
/**
* 校验工具类
*
*/
public class ValidationUtils {
private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
public static <T> ValidationResult validateEntity(T obj) {
ValidationResult result = new ValidationResult();
Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
// if( CollectionUtils.isNotEmpty(set) ){
if (set != null && set.size() != 0) {
result.setHasErrors(true);
Map<String, String> errorMsg = new HashMap<String, String>();
for (ConstraintViolation<T> cv : set) {
errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());
}
result.setErrorMsg(errorMsg);
}
return result;
}
public static <T> ValidationResult validateProperty(T obj, String propertyName) {
ValidationResult result = new ValidationResult();
Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, Default.class);
if (set != null && set.size() != 0) {
result.setHasErrors(true);
Map<String, String> errorMsg = new HashMap<String, String>();
for (ConstraintViolation<T> cv : set) {
errorMsg.put(propertyName, cv.getMessage());
}
result.setErrorMsg(errorMsg);
}
return result;
}
}
校验工具类返回的数据ValidationResult(省略getset):
package com.aliyun.prophet.facade.partner.flaw;
import java.util.Map;
/**
* 校验结果
*
*/
public class ValidationResult {
// 校验结果是否有错
private boolean hasErrors;
// 校验错误信息
private Map<String, String> errorMsg;
}
Person类(省略getset):
package com.aliyun.prophet.facade.partner.flaw;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
public class Person {
@Length(max=20,message="姓名长度不能大于20")
@NotEmpty(message="姓名不能为空")
private String name;
@Range(min = 0, max = 1, message = "性别只能输入只能输入0或1")
private Integer gender;
private Integer age;
}
使用方法:
/**
*
*/
public class Test {
@org.junit.Test
public void testValidation(){
Person person = new Person();
person.setAge(12);
person.setGender(2);
// person.setName("江南飞鹏");
ValidationResult result = ValidationUtils.validateEntity(person);
Map<String, String> map = result.getErrorMsg();
boolean isError = result.isHasErrors();
System.out.println("isError: " +isError);
System.out.println(map);
}
}
打印结果:
isError: true
{gender=性别只能输入只能输入0或1, name=姓名不能为空}