前言
提示:参数校验我们是基于spring-boot-starter-validation来做的,但是允许传入某些参数的校验需要我们自定义
怎么引入spring-boot-starter-validation,参考之前的文章点这里
一、场景
经常我们需要前端传入一些定义的枚举或者常量的字段,后台需要对传入的字段进行校验,验证传入参数是不是之前约定好的。
二、自定义AllowValue校验
自定义注解
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RUNTIME)
@Constraint(validatedBy = AllowValueImpl.class)
public @interface AllowValue {
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String message() default "not allow value";
String value();
boolean required() default false;
}
验证实现类
public class AllowValueImpl implements ConstraintValidator<AllowValue, Object> {
private String value;
private boolean required;
@Override
public void initialize(AllowValue constraint) {
this.value = constraint.value();
this.required = constraint.required();
}
@Override
public boolean isValid(Object obj, ConstraintValidatorContext context) {
if (null != obj) {
if (StringUtils.isNotEmpty(value)) {
String[] split = value.split(",");
if (split.length > 0) {
for (String s : split) {
if (obj instanceof String){
if (s.equals(obj)) {
return true;
}
}else if (obj instanceof Integer){
if ((obj).equals(Integer.parseInt(s))){
return true;
}
}
}
}
}
} else {
return required?false:true;
}
return false;
}
}
isValid 方法返回true或者false 如果为false时会将message错误信息返回出来。
二、实际使用
场景:我们需要前端调用接口进行数据审核,我们定义了两个code
- ACCEPT 审核通过
- REJECT 审核驳回
@Data
@EqualsAndHashCode(callSuper = false)
public class CompanyAttributeApprovalDto {
@NotNull
private Long id;
@NotNull
@AllowValue(value = "ACCEPT,REJECT",message = "审核状态错误")
private String auditStatus;
private String rejectReason;
}
controler
@PostMapping("/approval")
public CommonResult<Boolean> approval(@RequestBody @Valid CompanyAttributeApprovalDto approvalDto){
// 通过或驳回
return CommonResult.Success(true);
}
controler接收到参数时会校验,传入的参数是否符合@AllowValue注解的value中约定的参数。