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");
//調(diào)用驗證法方法
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)//注解實現(xiàn)類
@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;//對應(yīng)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即為傳入的參數(shù)值,此處是傳入的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");//名字設(shè)置為Lucy
輸出:
str-Jimmy
value--Lucy
id不能為空
stu.setName("Jimmy");//名字設(shè)置為Jimmy
輸出:
str-Jimmy
value--Jimmy
-----------true
id不能為空
名字不能為Jimmy
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者