hibernate Validator 的使用

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. 根据业务添加到需要的应用场景中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值