springboot 接口层参数校验 自定义参数校验
1.首先基本参数校验实现。
包含3步:DTO层,WEB层,全局异常捕获层。
1.1 DTO层。@NotNull @NotEmpty等
@Data
public class GnssMonitorPointCreateCmd {
@NotEmpty(message = "测站名字不能为空")
@ApiModelProperty("测站名字")
private String name;
@NotEmpty(message = "工程ID不能为空")
@ApiModelProperty("测站编码")
private String code;
}
1.2 Controller层。@Validated
@ApiOperation("新增")
@Log(title = "监测点", businessType = BusinessType.INSERT)
@PostMapping
public ResultMsg add(@RequestBody @Validated GnssMonitorPointCreateCmd createCmd) {
// do biz
}
1.3 全局参数异常捕获。@GlobalExceptionHandler IllegalArgumentException InvalidFormatException
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler({IllegalArgumentException.class, InvalidFormatException.class})
@ResponseBody
public ResultMsg illegalArgumentExceptionHandler(IllegalArgumentException e) {
return ResultMsg.error(e.getMessage());
}
}
2. 接下来介绍自定义参数类型实现
业务背景:审核接口,需要传入审核类型。驳回=1,通过=2。
2.1 自定义枚举校验类型
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {EnumValueValidator.class})
public @interface EnumValue {
// 默认错误消息
String message() default "值不在有效范围内";
String[] strValues() default {};
int[] intValues() default {};
boolean isRequired() default true;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
2.2 枚举校验
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {
private String[] strValues;
private int[] intValues;
private boolean isRequired;
@Override
public void initialize(EnumValue constraintAnnotation) {
strValues = constraintAnnotation.strValues();
intValues = constraintAnnotation.intValues();
isRequired = constraintAnnotation.isRequired();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (value == null) {
return !isRequired;
}
if (value instanceof String) {
for (String s : strValues) {
if (s.equals(value)) {
return true;
}
}
} else if (value instanceof Integer) {
for (Integer s : intValues) {
if (s == value) {
return true;
}
}
}
return false;
}
}
2.3 controller使用
@PostMapping("/anon/testParam")
public void testParam(@RequestBody @Validated Params params) {
}
@Data
private static class Params {
@EnumValue(intValues = {1, 2})
private Integer status;
}