关于 Spring Boot 参数校验的启用
因为看到项目中 @Valid
/@Validated
注解有的加在 Class 上,有的加在方法参数上,所以测试一下到底哪些情况需要加,哪些不需要加。
分别设计了几种校验场景:
@GetMapping
+ 校验注解 + 基本类型@GetMapping
+@RequestParam
+ 校验注解 + 基本类型@GetMapping
+Object
类型@PostMapping
+@RequestBody
+Object
类型
然后分别在如下场景执行了测试:
- 在类上添加
@Valid
/@Validated
注解; - 在
Object
类型参数上添加@Valid
/@Validated
注解。
测试代码
测试结果见接口上的备注:
java
package me.liujiajia.web_validate_example;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Validated
@RestController
@RequestMapping("/user")
public class UserController {
/**
* 使用基本类型接收 GET 请求参数,并在参数上添加校验注解。
* 1. 在类上使用 @Validated 注解时,校验不通过会抛出 ConstraintViolationException 异常。
* 2. 不在类上添加 @Validate 注解时也会执行校验,校验不通过会抛出 HandlerMethodValidationException 异常。
*/
@GetMapping("hello")
public String query(@NotBlank @Length(max = 10) String name) {
return "hello,%s.".formatted(name);
}
/**
* 这个接口和上面的 hello 接口不同的地方在于参数上添加了 @RequestParam 注解。
* 1. 在类上使用 @Validated 注解时,校验不通过会抛出 ConstraintViolationException 异常。
* 2. 不在类上添加 @Validate 注解时也会执行校验,校验不通过会抛出 HandlerMethodValidationException 异常。
*/
@GetMapping("detail")
public Person query(@RequestParam @NotBlank @Length(max = 10) String name,
@RequestParam @Range(min = 18, max = 60) Integer age) {
var person = new Person();
person.setAge(age);
person.setName(name);
return person;
}
/**
* 使用 Object 对象接收 GET 请求参数。
* 1. 在参数上添加 @Valid 或 @Validated 注解时,校验不通过会抛出 MethodArgumentNotValidException 异常。
* 2. 不加 @Valid 或 @Validated 注解时,不会执行参数校验。
*/
@GetMapping("query")
public List<Person> query(@Valid Person person) {
return List.of(person);
}
/**
* 使用 Object 对象接收 POST 请求参数。
* 1. 在参数上添加 @Valid 或 @Validated 注解时,校验不通过会抛出 MethodArgumentNotValidException 异常。
* 2. 不加 @Valid 或 @Validated 注解时,不会执行参数校验。
*/
@PostMapping
public Person add(@Valid @RequestBody Person person) {
return person;
}
}
java
package me.liujiajia.web_validate_example;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;
@Data
public class Person {
@NotBlank
@Length(max = 10)
private String name;
@Range(min = 18, max = 60)
private Integer age;
}
java
package me.liujiajia.web_validate_example;
import jakarta.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import java.util.stream.Collectors;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<String> handleValidationException(ConstraintViolationException ex) {
System.out.println(ex.getClass().getName());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getConstraintViolations().stream()
.map(cv -> "%s:%s".formatted(cv.getPropertyPath(), cv.getMessage()))
.collect(Collectors.joining("\n")));
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<String> handleValidationException(MethodArgumentNotValidException ex) {
System.out.println(ex.getClass().getName());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getAllErrors().stream()
.map(oe -> "%s:%s".formatted(oe instanceof FieldError fe ? fe.getField() : oe.getObjectName(), oe.getDefaultMessage()))
.collect(Collectors.joining("\n")));
}
@ExceptionHandler(HandlerMethodValidationException.class)
public ResponseEntity<String> handleValidationException(HandlerMethodValidationException ex) {
System.out.println(ex.getClass().getName());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getParameterValidationResults().stream()
.flatMap(r -> r.getResolvableErrors().stream()
.map(e -> "%s:%s".formatted(r.getMethodParameter().getParameterName(), e.getDefaultMessage())))
.collect(Collectors.joining("\n")));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleValidationException(Exception ex) {
System.out.println(ex.getClass().getName());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage());
}
}
xml
<?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>3.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>me.liujiajia</groupId>
<artifactId>web-validate-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>web-validate-example</name>
<description>Demo project for Spring Boot</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</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.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
请求示例:
http
### 错误参数
GET http://localhost:8080/user/hello?name=12345678901
### 正确参数
GET http://localhost:8080/user/hello?name=1234567890
http
### 错误参数
GET http://localhost:8080/user/detail?name=12345678901&age=17
### 正确参数
GET http://localhost:8080/user/detail?name=1234567890&age=18
http
### 错误参数
GET http://localhost:8080/user/query?name=12345678901&age=17
### 正确参数
GET http://localhost:8080/user/query?name=1234567890&age=18
http
### 错误参数
POST http://localhost:8080/user
Content-Type: application/json
Accept: application/json
{
"name": "12345678901",
"age": 17
}
### 正确参数
POST http://localhost:8080/user
Content-Type: application/json
Accept: application/json
{
"name": "1234567890",
"age": 18
}
可以得到类似如下内容的报错信息:
txt
<!-- jakarta.validation.ConstraintViolationException -->
query.name:长度需要在0和10之间
query.age:需要在18和60之间
<!-- org.springframework.web.method.annotation.HandlerMethodValidationException -->
name:长度需要在0和10之间
age:需要在18和60之间
<!-- org.springframework.web.bind.MethodArgumentNotValidException -->
name:长度需要在0和10之间
age:需要在18和60之间
总结
- 直接在基本参数上添加的校验注解始终会起作用,只是如果在类上添加
@Validated
注解会改变抛出的异常的类型; - 使用
Object
类型的参数接收请求时,必须在方法的参数上添加@Valid
或@Validated
注解,否则对象字段上的校验注解不会起作用。