Hibernate Validator用法

一、Hibernate ValiDator介绍

Bean Validation是JSR303的定义,Hibernate Validator是对BeanValidation的实现,同时附加了几个自己的注解。

二、Hibernate Validator支持的注解 

Bean Validation 中内置的 constraint  
   
@Null   被注释的元素必须为 null  
@NotNull    被注释的元素必须不为 null  
@AssertTrue     被注释的元素必须为 true  
@AssertFalse    被注释的元素必须为 false  
@Min(value)     被注释的元素必须是一个数字,其值必须大于等于指定的最小值  
@Max(value)     被注释的元素必须是一个数字,其值必须小于等于指定的最大值  
@DecimalMin(value)  被注释的元素必须是一个数字,其值必须大于等于指定的最小值  
@DecimalMax(value)  被注释的元素必须是一个数字,其值必须小于等于指定的最大值  
@Size(max=, min=)   被注释的元素的大小必须在指定的范围内  
@Digits (integer, fraction)     被注释的元素必须是一个数字,其值必须在可接受的范围内  
@Past   被注释的元素必须是一个过去的日期  
@Future     被注释的元素必须是一个将来的日期  
@Pattern(regex=,flag=)  被注释的元素必须符合指定的正则表达式  
  
Hibernate Validator 附加的 constraint  
@NotBlank(message =)   验证字符串非null,且长度必须大于0  
@Email  被注释的元素必须是电子邮箱地址  
@Length(min=,max=)  被注释的字符串的大小必须在指定的范围内  
@NotEmpty   被注释的字符串的必须非空  
@Range(min=,max=,message=)  被注释的元素必须在合适的范围内  

三、代码演示

1.pom文件

   <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.Bean

public class Student {
    interface GroupA {}

    interface GroupB {}

    interface GroupC {}

    @NotNull(message = "姓名不能为空", groups = GroupA.class)
    private String name;
    private int age;
    @Range(min = 1, max = 2, groups = GroupB.class)
    private Double money;
    @Size(min = 1, max = 3)
    private String address;

    @Size(min = 1, max = 2, groups = GroupC.class)
    private List<String> registerClass;
    @Email(groups = GroupB.class)
    private String email;

3.验证代码

 public static void main(String[] args) {
        Student student = new Student();
        //student.setName("Tom");
        student.setAddress("浙江省杭州市");
        student.setAge(101);
        student.setMoney(101D);
        student.setEmail("as");
        student.setRegisterClass(Lists.newArrayList("Englist","Math","haha"));
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();


        Set<ConstraintViolation<Student>> constraintViolationSet =  validator.validate(student, GroupA.class,GroupB.class);
        for (ConstraintViolation<Student> constraintViolation : constraintViolationSet) {
            System.out.println(constraintViolation.getPropertyPath() + constraintViolation.getMessage());
        }
    }

除了支持基本已经实现的验证功能之外,还支持分组,针对不同组进行验证。

 

四、Bean Validator的扩展

下面实现一个Validator,目的是检测一个List里面的所有元素在一定的范围,如果超过一定的范围或者不是Number类型的就返回提示

1.定义一个validator注解

@Constraint(validatedBy = CheckListRangeValidator.class)
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CheckListRange {
    String message() default "{List里面的元素必须大于min 小于max}";

    int min() default Integer.MIN_VALUE;

    int max() default Integer.MAX_VALUE;

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

2.validator的实现

public class CheckListRangeValidator implements ConstraintValidator<CheckListRange, List> {

    private int min;
    private int max;

    public void initialize(CheckListRange constraintAnnotation) {
        this.min = constraintAnnotation.min();
        this.max = constraintAnnotation.max();
    }

    public boolean isValid(List value, ConstraintValidatorContext context) {
        for (Object object : value) {
            if (object == null || !(object instanceof Number)) {
                return false;
            }

            if (((Number)object).doubleValue() < min || ((Number)object).doubleValue() > max) {
                return false;
            }
            return true;
        }

        return false;

    }

}

3.Bean里面使用自定义validator注解

public class Student {
    interface GroupA {}

    interface GroupB {}

    interface GroupC {}

    @NotNull(message = "姓名不能为空", groups = GroupC.class)
    private String name;
    private int age;
    @Range(min = 1, max = 2, groups = GroupB.class)
    private Double money;
    @Size(min = 1, max = 3)
    private String address;

    @Size(min = 1, max = 2, groups = GroupC.class)
    private List<String> registerClass;
    @Email(groups = GroupB.class)
    private String email;


    @CheckListRange(min = 1, max = 100, message = "List中元素必须在大于等于1,小于等于100", groups = GroupC.class)
    //当使用自定义注解的时候一定要加上@Valid不然不会被识别
    @Valid  
    private List<? extends  Number> scoreList;

}

4.检测代码

public class MainTest {
    public static void main(String[] args) {
        Student student = new Student();
        //student.setName("Tom");
        student.setAddress("浙江省杭州市");
        student.setAge(101);
        student.setMoney(101D);
        student.setEmail("as");
        student.setRegisterClass(Lists.newArrayList("Englist","Math","haha"));

        student.setScoreList(Lists.newArrayList(-1.1D,3D,3D,3D));

        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();


        Set<ConstraintViolation<Student>> constraintViolationSet =  validator.validate(student, GroupC.class);
        for (ConstraintViolation<Student> constraintViolation : constraintViolationSet) {
            System.out.println(constraintViolation.getPropertyPath() + constraintViolation.getMessage());
        }
    }
}

5.最后结果

四月 01, 2017 2:36:54 下午 org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 5.3.4.Final
name姓名不能为空
scoreListList中元素必须在大于等于1,小于等于100
registerClass个数必须在1和2之间

Process finished with exit code 0

五、Spring MVC中的使用

/**
     * 备注:此处@Validated(PersonAddView.class) 表示使用PersonAndView这套校验规则,若使用@Valid 则表示使用默认校验规则,

    @RequestMapping(value = "/student", method = RequestMethod.POST)
    public void addStudent(@RequestBody @Validated({GroupC.class}) Student student) {
        System.out.println(student.toString());
    }

    /**
     * 修改Person对象
     * 此处启用PersonModifyView 这个验证规则
     */
    @RequestMapping(value = "/student", method = RequestMethod.PUT)
    public void modifyStudent(@RequestBody @Validated(value = {GroupA.class}) Student student) {           System.out.println(student.toString());
    }

 

转载于:https://my.oschina.net/u/2250599/blog/872199

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值