2019独角兽企业重金招聘Python工程师标准>>>

一、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

Hibernate Validator用法相关推荐

  1. Hibernate Validator JSR303示例教程

    Hibernate Validator JSR303示例教程 欢迎使用Hibernate Validator示例教程.数据验证是任何应用程序的组成部分.您将使用Javascript在表示层找到数据验证 ...

  2. springboot使用hibernate validator校验

    回到顶部 一.参数校验 在开发中经常需要写一些字段校验的代码,比如字段非空,字段长度限制,邮箱格式验证等等,写这些与业务逻辑关系不大的代码个人感觉有两个麻烦: 验证代码繁琐,重复劳动 方法内代码显得冗 ...

  3. Spring Validation(使用Hibernate Validator)

    1.需要的jar包 hibernate-validator.5.1.3.Final.jar validation-api.1.1.0.Final.jar 2.springsevlet-config.x ...

  4. Springmvc的服务端数据验证-----Hibernate Validator

    导入Hibernate validator的Jar包 hibernate-validator-4.3.0.Final.jar jboss-logging-3.1.0.CR2.jar validatio ...

  5. spring boot 1.4默认使用 hibernate validator

    spring boot 1.4默认使用 hibernate validator 5.2.4 Final实现校验功能.hibernate validator 5.2.4 Final是JSR 349 Be ...

  6. SpringBoot中使用Hibernate Validator校验工具类

    1.说明 在Spring Boot已经集成Hibernate Validator校验器的情况下, 对于配置了校验注解的请求参数, 框架会自动校验其参数, 但是如果想手动校验一个加了注解的普通对象, 比 ...

  7. 自定义Hibernate Validator规则注解

    自定义规则注解 除了使用已定义的校验规则外,我们也可以根据自定的业务自定义校验规则,接下来我们介绍一下如何自定义 Hibernate Validator校验规则. 创建自定义规则无参数注解介绍 声明自 ...

  8. SpringBoot 2 快速整合 | Hibernate Validator 数据校验

    概述 在开发RESTFull API 和普通的表单提交都需要对用户提交的数据进行校验,例如:用户姓名不能为空,年龄必须大于0 等等.这里我们主要说的是后台的校验,在 SpringBoot 中我们可以通 ...

  9. org/hibernate/validator/internal/engine

    java.lang.NoClassDefFoundError: org/hibernate/validator/internal/engine/DefaultParameterNameProvider ...

最新文章

  1. 微服务架构实践之服务注册发现与调用
  2. r语言electricity数据集_R语言学习10-查看数据
  3. 作者:高丰,英国南安普敦大学计算机博士,现为开放数据与创新独立咨询顾问,兼复旦大学数字与移动治理实验室特邀研究员。...
  4. shell脚本如何优雅的打印帮助信息
  5. 【译】用 Chrome 开发者工具以及 react 16 版本分析性能
  6. jmeter重写java请求_jmeter之编写java请求-扩展Java Sampler
  7. AtomicInteger 的使用
  8. SpringCloud 实战:禁止直接访问后端服务
  9. matlab中设置拟合初值,如何确定自定义函数拟合时的参数初值?
  10. 【学习】如何用jQuery获取iframe中的元素
  11. 2022数学建模“五一杯”B题
  12. 干货分享:【IT-PMP学堂】PMP 文档与配置管理
  13. JavaSE重点之集合、IO、多线程
  14. 基于stm32及sim800c sim868 实现的远程控制 小程序控制模块 源码 移植过程简介
  15. C++17新属性详解
  16. 【小技巧】腾讯QQ——腾讯网迷你版弹窗
  17. 心形一行python_心的解释|心的意思|汉典“心”字的基本解释
  18. Ubuntu 安装及基本配置(显示、镜像源、网络配置)
  19. java查找文件路径_如何查找java路径?
  20. APP Designer 制作简易英汉词典的回调函数书写

热门文章

  1. 关闭window端口445
  2. 有些事儿,工程师可能今生仅此一次
  3. protel快捷键大全
  4. hdu 4454 Stealing a Cake(三分之二)
  5. 老外听到哪些中式英文是崩溃的?(转自外贸Jackson)
  6. 带你遍历用户生命价值与流失挽救(上) : 流量下的价值套路
  7. 怎么才能判断一个产品用户体验的好坏?
  8. PMCAFF | 团队有20名产品经理,如何争取更多开发资源?
  9. 【干货】CRM大牛告诉你,Salesforce到底是个什么鬼?
  10. 【持续..】WEB前端面试知识梳理 - CSS部分