通过Validator接口实现
引入相关依赖
<dependencies>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>7.0.5.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.el</artifactId>
<version>4.0.1</version>
</dependency>
</dependencies>
创建实体类,定义属性和方法
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
创建类实现Validator接口,实现接口方法指定校验规则
public class PersonValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Person.class.equals(clazz);
}
@Override
public void validate(Object object, Errors errors) {
//name 不能为空
ValidationUtils.rejectIfEmpty(errors, "name", "name.empty","name is empty");
Person p = (Person) object;
//age 不能小于0 && 不能大于110
if (p.getAge() < 0) {
errors.rejectValue("age", "age.value.error", "error age < 0");
} else if (p.getAge() > 110) {
errors.rejectValue("age", "age.value.error.old", "error age >110");
}
}
}
上面定义的类,其实就是实现接口中对应的方法,
supports方法用来表示此校验用在哪个类型上,
validate是设置校验逻辑的地点,其中ValidationUtils,是Spring封装的校验工具类,帮助快速实现校验。
使用上述Validator进行测试
public class TestMethod1 {
public static void main(String[] args) {
// 创建person对象
Person person = new Person();
person.setName("lucy");
person.setAge(-1);
// 创建Person对应的DataBinder
DataBinder binder = new DataBinder(person);
// 设置校验
binder.setValidator(new PersonValidator());
// 执行校验
binder.validate();
// 输出结果
BindingResult results = binder.getBindingResult();
System.out.println(results.getAllErrors());
}
}
标签:name,Person,age,校验,接口,Spring42,person,Validation,public
From: https://www.cnblogs.com/Ashen-/p/17105675.html