Spring Boot 参数校验

参考

简单实现参数校验

  1. 添加依赖参数校验所需依赖
    1
    2
    3
    4
    5
    <!-- 参数校验  -->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
  2. 添加参数校验注解:在要校验的类中添加参数校验注解如age
    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
    public class TestJson {

    private String name;

    @Min(value = 1, message = "年龄必须大于等于1")
    @Max(value = 160, message = "年龄必须小于等于160")
    private int age;

    public TestJson(String name, int age) {
    this.name = name;
    this.age = age;
    }

    public String getName() {
    return name;
    }

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

    public int getAge() {
    return age;
    }

    public void setAge(int age) {
    this.age = age;
    }
    }
  3. 添加参数校验接口:在传入的参数中添加@Validated注解
    1
    2
    3
    4
    @PostMapping("/json")
    public TestJson json(@Validated @RequestBody TestJson json) {
    return json;
    }