bean validation自带的注解验证
<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>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
public class Student implements Serializable{
private static final long serialVersionUID = 1L;
@NotNull(message = "id不能为空")
private Integer id;
private String name;
//省略getter,setter
}
private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
public static <T> void main(String[] args) {
Student stu = new Student();
stu.setId(null);
stu.setName("Jimmy");
//调用验证法方法
validate(stu);
}
//验证
public static<T> void validate(T t){
Validator validator = factory.getValidator();
Set<ConstraintViolation<T>> constraintViolations = validator.validate(t);
for(ConstraintViolation<T> constraintViolation : constraintViolations) {
System.out.println(constraintViolation.getMessage());
}
}
id不能为空
自定义注解验证
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Target( {ElementType.METHOD,ElementType.TYPE,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CheckCaseValidator.class)//注解实现类
@Documented
public @interface CheckCase {
String message() default " ";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String value();
}
/**
* 自定义注解验证
* @author zhoucheng
*
*/
public class CheckCaseValidator implements ConstraintValidator<CheckCase, Object> {
private String str;//对应CheckCase注解中的value类型
@Override
public void initialize(CheckCase constraintAnnotation) {
this.str = constraintAnnotation.value();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if(value == null){
return true;
}
System.out.println("str-"+str);//str即为声明的注解值Jimmy
System.out.println(value.toString()+"====");//value即为传入的参数值,此处是传入的name的值Lucy
if(str.equals(value.toString())){
System.out.println("-----------true");
return true;
}
return false;
}
}
@CheckCase(value = "Jimmy",message="名字不能为Jimmy")
private String name;
stu.setName("Lucy");//名字设置为Lucy
输出:
str-Jimmy
value--Lucy
id不能为空
stu.setName("Jimmy");//名字设置为Jimmy
输出:
str-Jimmy
value--Jimmy
-----------true
id不能为空
名字不能为Jimmy