spring boot 参数校验
添加依赖
- 添加如下依赖,springboot自动帮我们开启校验
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
- 在springboot
使用方式
- 在Controller类上使用
@Validated
@RestController
@RequestMapping(value = "/user/")
@Validated
public class UserController {
...
}
- 在需要校验的请求参数前添加
@Valid
@PutMapping
public Result addBlog(@Valid @RequestBody UserTestRequest request) {
return Result.success("新增成功");
}
- 数据库操作保存前会进行校验
可用注解
- 包
jakarta.validation.constraints
下的注解 - 包
org.hibernate.validator.constraints
下的注解
自定义注解的使用
- 自定义注解,指定校验器
ValuesInEnum
@interface
@Documented
@Constraint(
validatedBy = {ValueInEnumValidator.class} //指定校验器,该校验器自定义校验逻辑
)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(ValuesInEnum.List.class)
public @interface ValuesInEnum {
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/*** 支持的枚举值 */
String[] enums() default {};
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface List {
ValuesInEnum[] value();
}
}
- 实现校验器
通过实现jakarta.validation.ConstraintValidator
接口完成自定义注解
ValueInEnumValidator.class
//A 注解类型,注解标注的对象类型
public interface ConstraintValidator<A extends Annotation, T> {
default void initialize(A constraintAnnotation) {
}
boolean isValid(T var1, ConstraintValidatorContext var2);
}
#具体实现
public class ValueInEnumValidator implements ConstraintValidator<ValuesInEnum, Object> {
private String[] enums;
@Override
public void initialize(ValuesInEnum constraintAnnotation) {
ConstraintValidator.super.initialize(constraintAnnotation);
enums = constraintAnnotation.enums();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (enums.length == 0) {
return true;
}
if (Objects.isNull(value)) {
return false;
}
return Arrays.stream(enums).anyMatch(e ->
Objects.equals(String.valueOf(e), String.valueOf(value))
);
}
}
- 使用注解
#请求参数
public class UserTestRequest extends AbstractRequest {
@NotBlank(message = "id不能为空")
private String id;
@NotNull(message = "审批状态不能为空")
@ValuesInEnum(enums = {"1", "2", "3"}, message = "审批状态必须为[1,2,3]")
@FieldDesc(name = "审批状态")
private Integer status;
public UserTestRequest() {
}
public UserTestRequest(String id, Integer status) {
this.id = id;
this.status = status;
}
public UserTestRequest(HttpRequest request, HttpResponse response, String id, Integer status) {
super(request, response);
this.id = id;
this.status = status;
}
public String getId() {
return id;
}
public Integer getStatus() {
return status;
}
}
#controller
@RestController
@RequestMapping(value = "/user/")
public class UserController {
@PutMapping
public Result addBlog(@Valid @RequestBody UserTestRequest request) {
return Result.success("新增成功");
}
}