posts - 101,comments - 5,views - 14万

项目开发中会针对上游传过来的数据集中特定字段做一些校验

 

1.特定字段非空校验 @Validate @NotNull

复制代码
@Immutable
@Data
public class MetaData{
  @Valid
  @NotNull
  private CommonMetaData commonMeta;
  @Valid
  @NotNull
  @Indexed
  private Integer businessDate;
  private Integer version=1;
  private Map<String, String> generatedFrom;
  private Long sourceTimestamp;
}
View Code
复制代码
复制代码
    public <T> void schemaValidate(SpecificRecordBase specificRecordBase){
        T t=getResult(specificRecordBase);
        if(null!=t) {
            Set<ConstraintViolation<T>> set = Validation.buildDefaultValidatorFactory().getValidator().validate(t); //针对t进行校验是否有空值
            List<String> errorList = new ArrayList<>();
            if (set != null && !set.isEmpty()) {
                for (ConstraintViolation<T> cv : set) {
                    String property = cv.getPropertyPath().toString();
                    StringBuilder sb = new StringBuilder();
                    sb.append(cv.getMessage());
                    errorList.add(property + ":" + sb);
                }
            }
            if (!CollectionUtils.isEmpty(errorList)) {
                throw new ValidateException(400, errorList.toString());
            }
        }else{
            throw new ValidateException(400,"Input Is Null");
        }
    }

    public <T> T getResult(SpecificRecordBase specificRecordBase) {
        return (T) gson.fromJson(specificRecordBase.toString(),BondQuoteData.class);
    }
View Code
复制代码

 

2. 特定字段的特殊业务逻辑校验 @Constraint

2.1 Data:

复制代码
@Data
public class VlaueData {
    @Valid
    @NotNull
    @ValueConstraint
    private String id;
}
View Code
复制代码

2.2 controller:

controller层加上@Validate注解便可以实现对自定义注解字段的校验

复制代码
  @ApiOperation(value = "Save a list of BondQuote by putting service.")
  @PutMapping(value = "/v2/xip/markets/quotes", consumes = {MediaType.APPLICATION_JSON_VALUE},
      produces = {MediaType.APPLICATION_JSON_VALUE})
  @ResponseStatus(HttpStatus.OK)
  public void validate(@RequestBody @Valid VlaueData vlaueData){
    constraintTest.valueProcess();
  }
View Code
复制代码

 

2.3 自定义注解类 ValueConstraint  

这个类中定义校验类

复制代码
@Documented
@Constraint(validatedBy = ValueValidate.class)
@Target({METHOD, FIELD, PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface ValueConstraint {
    String message() default
      "error input";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}
View Code
复制代码

 

2.4 校验类 ValueValidate

校验类实现 ConstraintValidator<ValueConstraint, String> 第一个参数对应2.3中自定义注解类,第二个参数对应2.1中要校验的参数类型

 

复制代码
public class ValueValidate implements ConstraintValidator<ValueConstraint, String> {//第一个参数:@Interface自定义的注解类;第二个参数:要校验的数据类型
    public static final String specificBusinessDatePattern = "^(\\d{8})$";

    @Override
    public void initialize(ValueConstraint constraintAnnotation) {

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (!isIntValue(value)) {
            return false;
        }
        return true;
    }

    public boolean isIntValue(String string) {
        return string.matches(specificBusinessDatePattern);
    }
}
View Code
复制代码

 

当输入参数满足2.4中isValid()返回false时,校验不通过,返回异常response

 

 

 

输入参数满足2.4中isValid()返回true时,校验通过继续往下走

 

posted on   colorfulworld  阅读(1245)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示