1. maven 依赖:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.2.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>
2. 测试方法:
public static Validator stringToDate(){
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Person person = new Person();
person.setId(1);
person.setAddress("aa");
person.setAge(28);
person.setEmail("cc");
person.setCrtTime(new Date());
Set<ConstraintViolation<Person>> constraintViolations = validator.validate(person);
for(Iterator<ConstraintViolation<Person>> i = constraintViolations.iterator(); i.hasNext();) {
ConstraintViolation<Person> v = i.next();
System.out.println(v.getPropertyPath());
System.out.println(v.getMessage());
}
return validator;
}
public static void main(String[] args) {
stringToDate();
}
public class Person {
@Range(min=10,max=20,message="大小不在范围内")
private Integer id;
@Min(value=9,message="数据太小")
private Integer age;
@Length(min=6,max=50,message="地址长度不在范围内")
private String address;
@Email(message="email格式不对")
private String email;
@NotNull
private Date crtTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCrtTime() {
return crtTime;
}
public void setCrtTime(Date crtTime) {
this.crtTime = crtTime;
}
}
3. 根据业务添加到需要的应用场景中