SpringBoot优雅的进行参数合规校验

参考来源:
https://blog.csdn.net/mr_wanter/article/details/124406749?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2

非空校验

在实体类中使用@NotNull@NotEmpty@NotBlank注解,加在需要进行非空校验的参数上。

1.@NotNull:不能为null,但可以为empty

(""," "," ")

2.@NotEmpty:不能为null,而且长度必须大于0

(" "," ")

3.@NotBlank:只能作用在String上,不能为null,而且调用trim()后,长度必须大于0

("test") 即:必须有实际字符

举个栗子:

1.String name = null;
@NotNull: false
@NotEmpty:false
@NotBlank:false
2.String name = "";
@NotNull:true
@NotEmpty: false
@NotBlank: false
3.String name = " ";
@NotNull: true
@NotEmpty: true
@NotBlank: false
4.String name = "Great answer!";
@NotNull: true
@NotEmpty:true
@NotBlank:true

在接口获取参数时,加入@Valid注解进行校验

    @PostMapping("/addUpdateRefundmentApply")
    @ApiOperation("我只是一个无辜的描述")
    public Result addUpdateRefundmentApply(@Valid @RequestBody RefundmentApplyCreateRequest request) {
        try {
            String no = scmHx07RefundmentapplyheadService.addUpdateRefundmentApply(request);
            return Result.success(no);
        }catch(FinanceException e) {
            log.error("我只是一个无辜的报错 error",e);
            return Result.error(e.getMessage());
        }catch(Exception e) {
            log.error("我只是一个无辜的报错 error",e);
            return Result.error("退款申请单保存失败");
        }
    }

实体类中使用如下:

@ApiModel("新增、修改退款申请单退款银行信息明细接口入参")
@Data
public class RefundmentApplyDtlRequest {

    @ApiModelProperty("款项来源")
    private String applySource;

    @NotNull(message = "款项来源不能为空")
    @ApiModelProperty("款项来源Code")
    private Integer applySourceCode;

    @NotBlank(message = "开户行不能为空")
    @ApiModelProperty("开户行")
    private String receiveBank;

    @NotBlank(message = "银行账号不能为空")
    @ApiModelProperty("银行账号")
    private String bankAccount;

    @NotNull(message = "退款金额不能为空")
    @ApiModelProperty("退款金额")
    private BigDecimal amount;

    @NotNull(message = "配置标志不能为空")
    @ApiModelProperty("配置标志")
    private Integer refBillDtId;

    @NotBlank(message = "联行号不能为空")
    @ApiModelProperty("联行号")
    private String bankNumber;
}

参数范围校验

@Getter
@Setter
public class UserBO {

    /**
     * 用户名,长度在6-16个字符之间,必须参数
     */
    @NotBlank(message = "用户名不能为空")
    @Size(min = 6, max = 16, message = "用户名长度必须在6-16个字符之间")
    private String username;

    /**
     * 出生日期,格式为 yyyy-MM-dd,必须为过去的日期,不必须参数
     */
    @Past(message = "出生日期必须早于当前日期")
    @JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")
    private LocalDate birthday;

    /**
     * 等级,整数,0-5之间,必须参数
     */
    @NotNull(message = "用户等级不能为空")
    @Min(value = 0, message = "用户等级最小为0")
    @Max(value = 5, message = "用户等级最大为5")
    @Digits(integer = 1, fraction = 0, message = "用户等级必须为整数")
    private Integer level;

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容