Hibernate Validator用法

1、Hibernate ValiDator介紹

Bean Validation是JSR303的定義,Hibernate Validator是對BeanValidation的實現,同時附加了幾個本身的註解。java

2、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=)  被註釋的元素必須在合適的範圍內

3、代碼演示

1.pom文件git

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

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());
        }
    }

除了支持基本已經實現的驗證功能以外,還支持分組,針對不一樣組進行驗證。api

 

4、Bean Validator的擴展

下面實現一個Validator,目的是檢測一個List裏面的全部元素在必定的範圍,若是超過必定的範圍或者不是Number類型的就返回提示bash

1.定義一個validator註解app

@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的實現ui

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註解this

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.檢測代碼spa

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

5、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());
    }
相關文章
相關標籤/搜索