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;

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM