一、自定义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
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> set = validator.validate(student,First.class); for (ConstraintViolation constraintViolation : set) { System.out.println(constraintViolation.getMessage()); } }
参考:
http://elim.iteye.com/blog/1812584
http://blog.csdn.net/gaoshanliushui2009/article/details/50667017