SpringBoot之入参校验
前言
字段验证是我们代码规范的一个重要体现。大家都知道,在接口的每次入参都需要进行一次参数验证,那么,如何在SpringBoot项目中高效优雅的进行参数验证呢?
1. 引入依赖
<!-- Maven -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.7.5</version>
</dependency>
<!-- Gradle -->
implementation 'org.springframework.boot:spring-boot-starter-validation:2.7.5'
2. 使用说明
由于目前使用较流行的方式为@Validated,且功能要比@Valid强大,这里就不对@Valid进行介绍了…
二者区别:
1、@Validated是springboot框架里提供的注解,而@Valid是java包下的注解;
2、@Validated支持排序,@Valid不支持排序。
属性名 | 功能 |
---|---|
@NotNull(message = “提示信息”) | 非空校验(对于非String类型的变量都能使用) |
@NotBlank(message = “提示信息”) | 非空校验(针对String类型变量) |
@NotEmpty(message = “提示信息”) | 非空校验(比较鸡肋,只是针对null和空字符串,对于空格不会检查) |
@Max(value = 值,message = “提示信息”) | 表明该字段值不能超过xx |
@Min(value = 值,message = “提示信息”) | 表明该字段值不能小于xx |
… | … |
3.实例代码
controller层,给exportDto参数加上@Validated注解
@ApiOperation("测试Validated注解")
@PostMapping("/test/validated")
public MapMessage testValidated(@Validated @RequestBody ExportDto exportDto){
return MapMessage.successMessage();
}
model层,给exportDto类中需要校验的字段,加上相应的注解(例如@NotNull、NotBlank等)
@Data
public class ExportDto implements Serializable {
private static final long serialVersionUID = -5989040433802818872L;
/**
* @NotNull:表明这个字段必须不为 null, 否则报错BindException
*/
@ApiModelProperty("批次类别(1 - 大块废钢 2 - 废铁屑)")
@NotNull(message = "批次类别不能为空")
private Integer batchType;
/**
* @NotBlank:表明这个字段必须不为 null 或者 "" 或者 " "(检查时会忽略空格),否则报错BindException
*/
/*@ApiModelProperty("测试字段1")
@NotBlank(message = "ceShi1字段不能为空")
private String ceShi1;*/
/**
* @NotEmpty:表明这个字段必须不为 null 或者 "",否则报错BindException
*/
/*@ApiModelProperty("测试字段2")
@NotEmpty(message = "ceShi2字段不能为空")
private String ceShi2;*/
/**
* @Min:表明这个字段的值,不能小于3,否则报错BindException
*/
/*@ApiModelProperty("测试字段3")
@Min(value = 3,message = "ceShi3字段不能小于3")
private Integer ceShi3;*/
/**
* @Max:表明这个字段的值,不能大于20,否则报错BindException
*/
/*@ApiModelProperty("测试字段4")
@Max(value = 20,message = "ceShi4字段不能大于20")
private Integer ceShi4;*/
/**
* @Pattern:表明这个字段的值,必须匹配regexp属性中设置的正则表达式,否则报错BindException
*/
/*@ApiModelProperty("测试字段5")
@Pattern(regexp = "^[1][3,4,5,6,7,8,9][0-9]{9}$", message = "ceShi5字段必须是一个合法的手机号!")
private String ceShi5;*/
@ApiModelProperty("开始时间")
private Date startDate;
@ApiModelProperty("结束时间")
private Date endDate;
}
当校验失败时,会抛出异常BindException
我们只需要添加一个全局异常处理器,捕捉BindException异常,通过e.getFieldError().getDefaultMessage()就能获取到message属性中相应的提示信息
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BindException.class)
public MapMessage error(BindException e){
return MapMessage.errorMessage(Objects.requireNonNull(e.getFieldError()).getDefaultMessage());
}
}