您好,登錄后才能下訂單哦!
一、自定義annotation
摘自:http://elim.iteye.com/blog/1812584
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy=MinValidator.class)
public @interface Min {
int value() default 0;
String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class MinValidator implements ConstraintValidator<Min, Integer> {
private int minValue;
public void initialize(Min min) {
// TODO Auto-generated method stub
//把Min限制類型的屬性value賦值給當前ConstraintValidator的成員變量minValue
minValue = min.value();
}
public boolean isValid(Integer value, ConstraintValidatorContext arg1) {
// TODO Auto-generated method stub
//在這里我們就可以通過當前ConstraintValidator的成員變量minValue訪問到當前限制類型Min的value屬性了
return value >= minValue;
}
}
public class User {
private int age;
@Min(value=8, message="年齡不能小于8歲")
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
二、group校驗
public class Student implements Serializable { private static final long serialVersionUID = 1L; @NotBlank(message = "名稱不能為空", groups = { First.class }) private String name; @NotBlank(message = "年齡不能為空", groups = { Second.class }) private String age; ...省略get set方法 } public @interface First { } public @interface Second { } public static void main(String[] args){ Student student = new Student(); ValidatorFactory vf = Validation.buildDefaultValidatorFactory(); Validator validator = vf.getValidator(); Set<ConstraintViolation<student>> set = validator.validate(student,First.class); for (ConstraintViolation<student> constraintViolation : set) { System.out.println(constraintViolation.getMessage()); } }
參考:
http://elim.iteye.com/blog/1812584
http://blog.csdn.net/gaoshanliushui2009/article/details/50667017
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。