乐趣区

Spring-Boot数据校验

数据校验是一个相当重要的环节,使用 Spring Boot 进行数据校验。

添加校验依赖

全部依赖文件如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

添加配置文件

user:
  name:
    size: 用户名长度不符合要求
  age:
    size: 年龄输入不正确

添加数据校验

package com.example.demo;

import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Size;

public class User {
    private Integer id;
    // 其长度
    @Size(min = 5, max = 10, message = "{user.name.size}")
    private String name;
    // 其上限和下限
    @DecimalMax(value = "200", message = "{user.age.size}")
    @DecimalMin(value = "5", message = "{user.age.size}")
    private Integer age;
    // 省去 get 和 set
}

编写控制器

package com.example.demo;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {@PostMapping("/user")
    public List<String> addUser(@Validated User user, BindingResult bindingResult){List<String> errors = new ArrayList<>();
        // 非空
        if(bindingResult.hasErrors()){
            // 查找出 Error 进行添加到结果集
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError allError : allErrors) {errors.add(allError.getDefaultMessage());
            }
        }
        return errors;
    }
}

其中 BindingResult 类是用于保存错误信息的

测试

分组校验

添加分组接口

在实体类中添加分组信息

package com.example.demo;

import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Size;

public class User {
    private Integer id;
    // 其长度
    @Size(min = 5, max = 10, message = "用户名长度不符合要求", groups = ValidationGroup1.class)
    private String name;
    // 其上限和下限
    @DecimalMax(value = "200", message = "年龄输入不正确", groups = ValidationGroup2.class)
    @DecimalMin(value = "5", message = "年龄输入不正确", groups = ValidationGroup2.class)
    private Integer age;

    public Integer getId() {return id;}

    public void setId(Integer id) {this.id = id;}

    public String getName() {return name;}

    public void setName(String name) {this.name = name;}

    public Integer getAge() {return age;}

    public void setAge(Integer age) {this.age = age;}
}

控制器使用其分组

package com.example.demo;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {@PostMapping("/user")
    public List<String> addUser(@Validated(ValidationGroup2.class) User user, BindingResult bindingResult){List<String> errors = new ArrayList<>();
        // 非空
        if(bindingResult.hasErrors()){
            // 查找出 Error 进行添加到结果集
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError allError : allErrors) {errors.add(allError.getDefaultMessage());
            }
        }
        return errors;
    }
}

测试结果

微信公众号

退出移动版