zoukankan      html  css  js  c++  java
  • 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;
    
    }
    
  • 相关阅读:
    UVA 1599 Ideal Path(双向bfs+字典序+非简单图的最短路+队列判重)
    UVA 1572 Self-Assembly(拓扑排序)
    最大流当前弧优化Dinic分层模板
    POJ 3683.Priest John's Busiest Day 2-SAT
    n的m划分 整数拆分问题
    表达式计算
    大白书中无向图的点双联通分量(BCC)模板的分析与理解
    Codeforces 766D. Mahmoud and a Dictionary 并查集 二元敌对关系 点拆分
    树状数组入门
    Tire树入门专题
  • 原文地址:https://www.cnblogs.com/tuofan/p/13093488.html
Copyright © 2011-2022 走看看