zoukankan      html  css  js  c++  java
  • hibernate-validator校验框架学习

    1、引入jar包

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.4.1.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>

    注意:

    • 当使用hibernate-validator更高版本时,会报一个java.lang.ClassNotFoundException: javax.el.ELManager错误,目前博主还未找到兼容的方案,因此采用了5.4.1.Final版本。
    • 当不添加javax.el-api和javax.el依赖时,项目也可以运行,因为tomcat容器包含hibernate-validator所依赖的类

    2、spring-mvc配置

    <mvc:annotation-driven conversion-service="conversionService" validator="validator"/>
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
      <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
      <property name="validationMessageSource" ref="messageSource"></property>
    </bean>
    <!-- 检验错误信息资源配置文件 -->
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
      <property name="basenames">
        <list>
          <value>classpath:validator/validationMessages</value>
        </list>
      </property>
      <!-- 资源文件编码格式 -->
      <property name="fileEncodings" value="utf-8"/>
      <!-- 对资源文件内容的缓存时间,单位秒 -->
      <property name="cacheSeconds" value="120"/>
    </bean>

    3、在实体上增加相应注解校验信息

    private Integer stuId;
    @NotBlank(message = "{notnull}")
    @Size(max = 20, min = 2, message = "姓名长度在2-20之间")
    private String name;
    @Max(value = 200, message = "最大年龄200岁")
    @Min(value = 6, message = "最小年龄6岁")
    private Integer age;

    注意:

    message=“{notnull}”会去配置的错误文件中查找,即validator/validationMessages.properties文件中查找notnull的配置对应的错误信息。

    4、使用方式

    a) 自动校验

      在实体上增加@Validated注解,表示要校验这个实体。BindingResult用于接收验证后的错误信息。

    @RequestMapping(value = "/add", method = { RequestMethod.GET, RequestMethod.POST })
    public String addStudent(Model model, HttpServletRequest request, @Validated Student stu,
            BindingResult bindingResult) {
        if (HttpRequestContext.GET.equalsIgnoreCase(request.getMethod())) {
            return "prictice/student/addStudent";
        } else {
            if (bindingResult.hasErrors()) {
                List<ObjectError> errors = bindingResult.getAllErrors();
                model.addAttribute("errors", errors);
                return "prictice/student/addStudent";
            }
            stu.setRegTime(new Date());
            stu.setStatus(true);
            studentService.addStudent(stu);
            return "redirect:/student/list";
        }
    }

    b) 主动校验

    通过工具类,主动验证某个实体类

    新建工具类ValidateUtil.java

    public class ValidateUtil {
    
        public static <T> void validate(T obj) {
            LocalValidatorFactoryBean validator = (LocalValidatorFactoryBean) SpringContextHolder.getBean("validator");
            Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
            Iterator<ConstraintViolation<T>> iter = constraintViolations.iterator();
            while (iter.hasNext()) {
                ConstraintViolation<T> error = iter.next();
                StringBuffer buffer = new StringBuffer().append("[")
                        .append(error.getPropertyPath().toString()).append("]")
                        .append(error.getMessage());
                throw new IllegalArgumentException(buffer.toString());
            }
        }
    }

    或者可以使用下面的代码获取validator

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

     调用

    @RequestMapping(value = "/add")
    public String addStudent(@RequestParam Student stu) {
        ValidateUtil.validate(stu);
        return "redirect:/student/list"
    }

    5、常用注解

    注解

    作用

    AssertTrue

    布尔值为真

    AssertFalse

    布尔值为假

    Null

    引用为空

    NotNull

    引用不为空

    NotEmpty

    字符串引用和值都不是空

    Min

    数字的最小值

    Max

    数字的最大值

    Past

    日期必须是过去

    Future

    日期必须是未来

    Pattern

    字符串必须匹配正则表达式

    Valid

    递归验证引用

    Size

    验证字符串是否在Size范围内

    Email

    验证字符串是否是一个有效的电子邮箱

    URL

    字符串是否是一个有效的URL

    注意:

    • @NotEmpty 用在集合类上面
    • @NotBlank 用在String上面
    • @NotNull 用在基本类型上
    • @Email和@URL是Hibernate Validator自定义的,假如使用其他的Bean Validation实现,可能没有这两个注解。
    • 和JPA注解一样,如果验证注解添加到字段上,Hibernate就会直接读取字段的值。如果注解到Getter方法上,Hibernate就会调用方法取得值。在一个类中不要同时应用这两种方式,会导致重复验证的问题。
    • 如果在一个集合上应用Valid注解, Hibernate就会递归验证集合中的每一个元素。



  • 相关阅读:
    atitit.http get post的原理以及框架实现java php
    atitit.php中的dwr 设计模式
    Atitit.jquery 版本新特性attilax总结
    atitit.LimeSurvey 安装 attilax 总结
    atitit.php 流行框架 前三甲为:Laravel、Phalcon、Symfony2 attilax 总结
    atitit.项目设计模式---ioc attilax总结
    atitit.nfc 身份证 银行卡 芯片卡 解决方案 attilax总结
    atitit.提升研发效率的利器---重型框架与类库的区别与设计原则
    atitit。企业组织与软件工程的策略 战略 趋势 原则 attilax 大总结
    atitit.企业管理----商业间谍策略的使用与防务
  • 原文地址:https://www.cnblogs.com/lpob/p/10891511.html
Copyright © 2011-2022 走看看