• 13【JSR303校验】



    七、JSR303校验

    7.1 JSR303 简介

    Java Specification Requests:Java 规范提案简称JSR;JSR-303 是 JAVA EE 6 中的一项子规范,叫做 Bean Validation,官方参考实现是Hibernate Validator。JSR 303 用于对 Java Bean 中的字段的值进行验证。 Spring MVC 3.x 之中也大力支持 JSR-303,可以在控制器中对表单提交的数据方便地验证。

    7.2 JSR303提供的约束

    Tips:JSR303只是一个规范,我们具体的实现使用Hibernate Validator

    • JSR303 中内置的约束:
    约束说明
    @Null被标注字段必须为null
    @NotNull被标注字段必须不为null
    @AssertTrue被标注字段必须为true
    @AssertFalse被标注字段必须为false
    @Min(value)被标注字段必须是一个数字,并且值要大于等于value
    @Max(value)被标注字段必须是一个数字,并且值要小于等于value
    @DecimalMin(value)被标注字段必须是一个数字,并且值要大于等于value
    @DecimalMax(value)被标注字段必须是一个数字,并且值要小于等于value
    @Size(max,min)被标注字段必须是一个字符串,并且长度大于等于min,小于等于max
    @Digits(integer,fraction)被标注字段必须是一个数字,并且值必须在可接受的范围内
    @Past被标注字段必须是一个已经过去的日期
    @Future被标注字段必须是一个将来的日期
    @Pattern(value)被标注字段必须复合value中的正则表达式
    • Hibernate Validator新增的约束:
    约束说明
    @Email被标注字段必须是一个合法的邮箱
    @Length被标注字段必须在指定长度内
    @NotEmpty被标注字段必须必须非空
    @Range被标注的字段必须在指定范围内

    7.3 数据校验

    引入Hibernate-validator依赖:

    
    <dependency>
        <groupId>org.hibernategroupId>
        <artifactId>hibernate-validatorartifactId>
        <version>5.1.0.Finalversion>
    dependency>
    
    <dependency>
        <groupId>javax.elgroupId>
        <artifactId>javax.el-apiartifactId>
        <version>3.0.0version>
    dependency>
    
    <dependency>
        <groupId>org.glassfish.webgroupId>
        <artifactId>javax.elartifactId>
        <version>2.2.4version>
    dependency>
    
    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
        <version>1.18.22version>
    dependency>
    
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.13.1version>
        <scope>testscope>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    实体对象:

    package com.dfbz.entity;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import org.hibernate.validator.constraints.Email;
    import org.hibernate.validator.constraints.Range;
    
    import javax.validation.constraints.*;
    import java.util.Date;
    
    /**
     * @author lscl
     * @version 1.0
     * @intro:
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Emp {
    
        @NotNull                        // id不能为null
        private Integer id;             // 用户id
    
        @Size(min = 4, max = 8)         // 姓名在4-8位之间
        private String name;            // 员工姓名
    
        @Range(min = 18, max = 28, message = "年龄错了啊")      // 年龄在18-28岁之间
        private Integer age;            // 年龄
    
        @Email                          // 必须是合法email
        private String email;           // 邮箱
    
        @AssertTrue                     // 必须是true
        private Boolean sex;            // 性别  true:男 false:女
    
        @Digits(integer = 3, fraction = 2)           // 整数位必须在3位小数内(包含3位),小数位必须在2位之内(包含2位)
        private Double salary;          // 薪资
    
        @Past                           // 必须是一个已经过去的日期
        private Date birthday;          // 出生日期
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 测试代码:
    package com.dfbz.test;
    
    import com.dfbz.entity.Emp;
    import org.junit.Test;
    
    import javax.validation.ConstraintViolation;
    import javax.validation.Validation;
    import javax.validation.Validator;
    import javax.validation.ValidatorFactory;
    import java.util.Date;
    import java.util.Set;
    
    /**
     * @author lscl
     * @version 1.0
     * @intro:
     */
    public class Demo01 {
    
        @Test
        public void test1() {
            Emp emp = new Emp(null,
                    "administrator",
                    38, "admin.com",
                    false, 30.223D,
                    new Date(System.currentTimeMillis()+1000)
            );
    
            // 创建校验器工厂
            ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    
            // 通过工厂创建一个校验器
            Validator validator = factory.getValidator();
    
            // 通过校验器对指定的对象进行校验,获取校验清单
            Set<ConstraintViolation<Emp>> violations = validator.validate(emp);
    
            if (violations != null && violations.size() > 0) {
                for (ConstraintViolation<Emp> violation : violations) {
                    // 获取到每一个校验清单,打印清单值
                    System.out.println("Validation problem : " + violation.getMessage());
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    7.4 SpringMVC 数据校验

    • 准备表单:
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Titletitle>
    head>
    <body>
    <form action="/demo01/demo01" method="post">
        员工ID:<input type="text" name="id">
        员工姓名:<input type="text" name="name">
        员工年龄:<input type="text" name="age">
        员工邮箱:<input type="text" name="email">
        员工性别:<input type="text" name="sex">
        员工薪资:<input type="text" name="salary">
        出生日期:<input type="text" name="birthday">
        <input type="submit">
    form>
    
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • Controller:
    package com.dfbz.controller;
    
    import com.dfbz.entity.Emp;
    import org.springframework.stereotype.Controller;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.FieldError;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.validation.Valid;
    import java.util.List;
    
    /**
     * @author lscl
     * @version 1.0
     * @intro:
     */
    @Controller
    @RequestMapping("/demo01")
    public class Demo01Controller {
    
        /**
         * @param emp
         * @param result: 接收校验失败的信息,如果都校验成功则为空,如果没有BindingResult,则校验失败出现400错误
         * @Valid: 启用JSR303校验
         */
        @RequestMapping("/demo01")
        public ModelAndView demo01(@Valid Emp emp, BindingResult result) {
    
            ModelAndView mv=new ModelAndView("/success.jsp");
            if (result != null && result.getErrorCount() > 0) {
                // 说明有校验失败的字段
    
                // 获取所有验证不通过的field
                List<FieldError> fieldErrors = result.getFieldErrors();
    
                for (FieldError fieldError : fieldErrors) {
                    System.out.println(fieldError.getField() + ": " + fieldError.getDefaultMessage());
    
                    mv.addObject(fieldError.getField(),fieldError.getDefaultMessage());
                }
                mv.setViewName("/error.jsp");
            }
    
            System.out.println(emp);
            return mv;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
  • 相关阅读:
    HTML5期末大作业:美妆网页主题网站设计——清新的手工肥皂网站展示(4页)HTML+CSS+JavaScript
    alias linux 命令别名使用
    「认识AI:人工智能如何赋能商业」【29】主流的机器学习工具
    这Bug只能通过压测发现
    day35反射&动态代理
    [车联网安全自学篇] 二. IoT安全之树莓派4B/2W,烧写SD卡刷入Android 系统
    【无标题】
    云原生周刊:Kubernetes v1.31 发布
    脚手架应用场景之快速搭建项目
    C++-桶排/箱排
  • 原文地址:https://blog.csdn.net/Bb15070047748/article/details/128106017