# 整合参数校验
在 Spring Boot 中,使用 @Validated 注解可以对请求数据进行校验,常用于处理 API 请求的参数。你可以在控制器的方法参数上使用这些注解来确保数据的有效性。如果数据校验失败,Spring Boot 会自动抛出 MethodArgumentNotValidException 异常,你可以通过全局异常处理来统一处理这些异常。
# 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
# 数据传输对象
import javax.validation.constraints.*;
import org.hibernate.validator.constraints.Length;
import java.util.List;
import java.util.Date;
public class UserDTO {
@NotNull(message = "ID cannot be null")
private Long id;
@NotBlank(message = "Name cannot be blank")
private String name;
@Email(message = "Invalid email address")
private String email;
@Min(value = 18, message = "Age must be greater than or equal to 18")
@Max(value = 100, message = "Age must be less than or equal to 100")
private Integer age;
@Past(message = "Birthdate must be in the past")
private Date birthdate;
@Future(message = "Event date must be in the future")
private Date eventDate;
@Size(min = 1, max = 10, message = "Tags size must be between 1 and 10")
private List<String> tags;
@AssertTrue(message = "Active status must be true")
private Boolean active;
// Getters and setters
}
# 校验
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
@RestController
@RequestMapping("/users")
@Validated
public class UserController {
@PostMapping
public String createUser(@Valid @RequestBody UserDTO userDTO) {
// 如果 userDTO 校验通过,处理逻辑
return "User created successfully";
}
@GetMapping("/{id}")
public String getUser(@PathVariable @NotNull Long id) {
// 查询用户逻辑
return "User details";
}
}
# 全局校验异常处理
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.validation.FieldError;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach((error) -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
}
# 测试
发送一个无效的请求,例如:
{
"id": null,
"name": "",
"email": "invalid-email",
"age": 17,
"birthdate": "2025-01-01",
"eventDate": "2022-01-01",
"tags": [],
"active": false
}
你会得到一个带有详细校验错误的响应。
# 常用注解
@Xss 检查该字段是否存在跨站脚本工具
@Null 检查该字段为空
@NotNull 不能为null
@NotBlank 不能为空,常用于检查空字符串
@NotEmpty 不能为空,多用于检测list是否size是0
@Max 该字段的值只能小于或等于该值
@Min 该字段的值只能大于或等于该值
@Past 检查该字段的日期是在过去
@Future 检查该字段的日期是否是属于将来的日期
@Email 检查是否是一个有效的email地址
@Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式
@Range(min=,max=,message=) 被注释的元素必须在合适的范围内
@Size(min=, max=) 检查该字段的size是否在min和max之间,可以是字符串、数组、集合、Map等
@Length(min=,max=) 检查所属的字段的长度是否在min和max之间,只能用于字符串
@AssertTrue 用于boolean字段,该字段只能为true
@AssertFalse 该字段的值只能为false