分组校验
package com.example.demo.test;
import lombok.Data;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Set;
@Data
public class Student {
//主键
@NotNull(message="学生id不能为空",groups = {Update.class})
private String id;
//名称
@NotNull(message="姓名不能为空",groups = {Add.class,Update.class})
@Size(min=1, max=6,message="姓名长度为1~6",groups = {Add.class,Update.class})
private String name;
public interface Add{
}
public interface Update{
}
//验证代码
public static void main(String[] args) {
Student stu = new Student();
validate(stu,Student.Update.class); //更新情况下的校验
Student stu1 = new Student();
stu1.setId("1");
validate(stu,Student.Add.class);//新增情况下的校验
}
private static void validate(Object o,Class group){
ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
Validator validator = vf.getValidator();
Set<ConstraintViolation<Object>> set = validator.validate(o, group);
for (ConstraintViolation<Object> constraintViolation : set) {
System.out.println(constraintViolation.getPropertyPath()+":"+constraintViolation.getMessage());
}
}
}
运行mian函数结果如下:
手动实现参数校验
一般情况下,我们都是在springMVC的controller就行参数校验,由框架完成校验,那如何实现自己在其他地方,比如服务层,甚至在dao层进行校验呢?
其实springMVC也是调用了ValidatorImpl这个类,如图所示:
所以,我们可以使用ValidatorFactory实现手动的参数校验:
package com.example.demo.test;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.Set;
class Test{
private static class User {
@NotNull(message = "姓名不能为空")
private String name;
@Min(value = 1 ,message = "年龄不能小于0")
@NotNull(message = "age不能为空")
private Integer age;
@NotNull(message = "id不能为空")
private Integer id;
//省略get set方法
}
//验证代码
public static void main(String[] args) {
User user = new User();
validate(user);
}
private static void validate(Object o){
ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
Validator validator = vf.getValidator();
Set<ConstraintViolation<Object>> set = validator.validate(o);
for (ConstraintViolation<Object> constraintViolation : set) {
System.out.println(constraintViolation.getPropertyPath()+":"+constraintViolation.getMessage());
}
}
}
执行结果如下: