您的位置:首页 > 编程语言 > Java开发

还在写一堆if语句来校验前端传过来的参数吗?来看看spring boot如何优雅的处理参数校验

2020-07-19 04:25 405 查看

文章目录

前言

还在为接口写一堆if语句校验参数吗?快来使用@Validated 校验你的参数吧,写法优雅,逻辑清晰,你值得拥有。

spring boot中已经引入了@Validated 的基础包,所以在spring boot项目中我们可以直接使用。

更新:

spring boot最新版已经默认去掉了参数校验的包,需要手动引入依赖。

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

使用方法

1、首先在Controller接口的参数上加上@Validated 注解,表示要校验这个参数:

/**
* 添加员工信息
*
* @param param
* @return
*/
@ApiOperation("添加员工信息")
@PostMapping("addEmp")
public ResponseEntity<Boolean> addEmp(@RequestBody @Validated AddEmpParam param){
return ResponseEntity.success(empService.addEmp(param));
}

2、然后在Bean上声明需要被校验的字段:

/**
* 添加员工参数实体
* @author ZhengNC
* @date 2020/5/24 16:57
*/
@ApiModel("添加员工参数实体")
@Data
public class AddEmpParam {

/**
* 手机号
*/
@ApiModelProperty("手机号")
@NotBlank(message = "手机号不能为空")
private String phone;

/**
* 姓名
*/
@ApiModelProperty("姓名")
@NotBlank(message = "姓名不能为空")
private String name;

/**
* 性别:0 未知,1男,2女
*/
@ApiModelProperty("性别:0 未知,1男,2女")
@NotNull(message = "性别不能为空")
@Min(value = 0, message = "性别输入错误")
@Max(value = 2, message = "性别输入错误")
private Integer sex;

/**
* 年龄
*/
@ApiModelProperty("年龄")
@Min(value = 18, message = "年龄不能低于18岁")
private Integer age;

/**
* 身份证
*/
@ApiModelProperty("身份证")
@Pattern(regexp = "^\\d{15}|\\d{18}|\\d{17}(\\d|X|x)$", message = "身份证号码错误")
private String idCard;

}

3、最后,如果校验不通过就会抛出异常,可以在统一异常处理类中处理这些异常:

/**
* 全局异常处理
* @author ZhengNC
* @date 2020/5/24 20:17
*/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

/**
* 处理实体类参数校验异常
* @param e
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
return ResponseEntity.paramFailed(e.getBindingResult().getFieldError().getDefaultMessage());
}

/**
* 处理方法参数校验异常
* @param e
* @return
*/
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity handleConstraintViolationException(ConstraintViolationException e){
if (e.getConstraintViolations().size() > 0){
return ResponseEntity.paramFailed(
((ConstraintViolation)e.getConstraintViolations().toArray()[0])
.getMessageTemplate()
);
}
return ResponseEntity.paramFailed();
}

/**
* 处理SpringWeb参数校验异常
* @param e
* @return
*/
@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity handleMissingServletRequestParameterException(MissingServletRequestParameterException e){
return ResponseEntity.paramFailed();
}

/**
* 处理自定义响应类异常
* @param e
* @return
*/
@ExceptionHandler(ResponseException.class)
public ResponseEntity handleResponseException(ResponseException e){
log.error("{}", e.getStackTrace());
return ResponseEntity.failed(e.getCode(), e.getMessage());
}

/**
* 处理所有的运行时异常
* @param e
* @return
*/
@ExceptionHandler(RuntimeException.class)
public ResponseEntity handleRuntimeException(RuntimeException e){
log.error("{}", e.getStackTrace());
e.printStackTrace();
return ResponseEntity.failed();
}
}

常用的注解类型

@Pattern

校验的字符串必须满足指定的正则表达式

例:@Pattern(regexp = “^\d{15}|\d{18}|\d{17}(\d|X|x)$”, message = “身份证号码错误”)

可用类型:字符串

注意: null可以校验通过

@AssertFalse

校验的元素一定是假的

可用类型:boolean、Boolean

注意: null可以校验通过

@AssertTrue

校验的元素一定是真的

可用类型:boolean、Boolean

注意: null可以校验通过

@NotNull

不能为null

可用类型:所有

@Null

必须为null

可用类型:所有

@NotEmpty

不能为null且不能为空

可用类型:字符串、集合、Map、数组

@NotBlank

不能为null且至少有一个非空白字符

可用类型:字符串

@DecimalMax

校验的元素必须是数字,小数和整数都可以,且必须小于或等于指定的最大值(value为字符串类型)

可用类型:BigDecimal、BigInteger、字符串、(byte、short、int、long)以及它们的包装类型

注意: double和float不支持,null可以校验通过

@DecimalMin

校验的元素必须是数字,小数和整数都可以,且必须大于或等于指定的最小值(value为字符串类型)

可用类型:BigDecimal、BigInteger、字符串、(byte、short、int、long)以及它们的包装类型

注意: double和float不支持,null可以校验通过

@Max

校验的元素必须是数字,小数和整数都可以,且必须小于或等于指定的最大值(value为long类型)

可用类型:BigDecimal、BigInteger、(byte、short、int、long)以及它们的包装类型

PS:经验证 字符串 也是支持的类型

注意: double和float不支持,null可以校验通过

@Min

校验的元素必须是数字,小数和整数都可以,且必须大于或等于指定的最小值(value为long类型)

可用类型:BigDecimal、BigInteger、(byte、short、int、long)以及它们的包装类型

PS:经验证 字符串 也是支持的类型

注意: double和float不支持,null可以校验通过

@Negative

校验的元素必须是数字,且必须小于0

可用类型:BigDecimal、BigInteger、(byte、short、int、long、float、double)以及它们的包装类型

注意: null可以校验通过

@NegativeOrZero

校验的元素必须是数字,且必须小于或等于0

可用类型:BigDecimal、BigInteger、(byte、short、int、long、float、double)以及它们的包装类型

注意: null可以校验通过

@Positive

校验的元素必须是数字,且必须大于0

可用类型:BigDecimal、BigInteger、(byte、short、int、long、float、double)以及它们的包装类型

注意: null可以校验通过

@PositiveOrZero

校验的元素必须是数字,且必须大于或等于0

可用类型:BigDecimal、BigInteger、(byte、short、int、long、float、double)以及它们的包装类型

注意: null可以校验通过

@Digits

校验数字的精度,参数integer为整数位最大长度,fraction为小数位最大长度。

例如:@Digits(integer = 3, fraction = 1, message = “校验未通过”) //表示整数位最多3位,小数位最多1位

可用类型:BigDecimal、BigInteger、字符串、(byte、short、int、long)以及它们的包装类型

注意: null可以校验通过,参数fraction对小数位的校验只对BigDecimal和String生效,对于其它类型这个参数无效

@Email

校验的元素必须是一个结构完整的电子邮件地址

可用类型:字符串

注意: null可以校验通过

@Future

校验的元素必须是未来的瞬间,日期或时间

可用类型:

  • java.util.Date

  • java.util.Calendar

  • java.time.Instant

  • java.time.LocalDate

  • java.time.LocalDateTime

  • java.time.LocalTime

  • java.time.MonthDay

  • java.time.OffsetDateTime

  • java.time.OffsetTime

  • java.time.Year

  • java.time.YearMonth

  • java.time.ZonedDateTime

  • java.time.chrono.HijrahDate

  • java.time.chrono.JapaneseDate

  • java.time.chrono.MinguoDate

  • java.time.chrono.ThaiBuddhistDate

注意: null可以校验通过

@FutureOrPresent

校验的元素必须是现在或是未来的瞬间,日期或时间

可用类型:和 @Future 的可用类型相同

注意: null可以校验通过

@Past

校验的元素必须是过去的瞬间,日期或时间

可用类型:和 @Future 的可用类型相同

注意: null可以校验通过

@PastOrPresent

校验的元素必须是现在或是过去的瞬间,日期或时间

可用类型:和 @Future 的可用类型相同

注意: null可以校验通过

@Size

校验元素的尺寸必须在指定的范围内(包含边界)

例:@Size(min = 1, max = 5, message = “校验未通过”)

可用类型:字符串(校验字符串长度)、集合(校验Size)、Map(校验Size)、数组(校验length)

注意: null可以校验通过

@Valid

声明对实体类校验(嵌套校验会用到)

例如:

@Valid
private AddEmpParam empParam;

注意: null可以校验通过

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: