Hibernate Validator用法
生活随笔
收集整理的這篇文章主要介紹了
Hibernate Validator用法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
2019獨角獸企業(yè)重金招聘Python工程師標準>>>
一、Hibernate ValiDator介紹
Bean Validation是JSR303的定義,Hibernate Validator是對BeanValidation的實現(xiàn),同時附加了幾個自己的注解。
二、Hibernate Validator支持的注解?
Bean Validation 中內置的 constraint @Null 被注釋的元素必須為 null @NotNull 被注釋的元素必須不為 null @AssertTrue 被注釋的元素必須為 true @AssertFalse 被注釋的元素必須為 false @Min(value) 被注釋的元素必須是一個數(shù)字,其值必須大于等于指定的最小值 @Max(value) 被注釋的元素必須是一個數(shù)字,其值必須小于等于指定的最大值 @DecimalMin(value) 被注釋的元素必須是一個數(shù)字,其值必須大于等于指定的最小值 @DecimalMax(value) 被注釋的元素必須是一個數(shù)字,其值必須小于等于指定的最大值 @Size(max=, min=) 被注釋的元素的大小必須在指定的范圍內 @Digits (integer, fraction) 被注釋的元素必須是一個數(shù)字,其值必須在可接受的范圍內 @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());}}除了支持基本已經(jīng)實現(xiàn)的驗證功能之外,還支持分組,針對不同組進行驗證。
?
四、Bean?Validator的擴展
下面實現(xiàn)一個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的實現(xiàn)
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個數(shù)必須在1和2之間Process finished with exit code 0五、Spring MVC中的使用
/*** 備注:此處@Validated(PersonAddView.class) 表示使用PersonAndView這套校驗規(guī)則,若使用@Valid 則表示使用默認校驗規(guī)則,@RequestMapping(value = "/student", method = RequestMethod.POST)public void addStudent(@RequestBody @Validated({GroupC.class}) Student student) {System.out.println(student.toString());}/*** 修改Person對象* 此處啟用PersonModifyView 這個驗證規(guī)則*/@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
總結
以上是生活随笔為你收集整理的Hibernate Validator用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iOS 通过Jenkins 自动构建ip
- 下一篇: Android开发中adb命令的常用方法