1.validation与 springboot 结合,不在用传统代码里面if 判断
传统:
if(id==null){
throw new Exception(String.format("%s信息不存在!", id));
}
validation与 springboot 结合,添加依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2.实体上加上相关校验
@Data public class QuestionOrderVO implements Serializable { /** * 当前用户 */ @NotNull(message = "当前用户id不能为空") private Long userId; @Min(value = 1,message = "必须大于0") private Integer pageSize=1; @Range(min = 1,max = 1000,message = "一次性获取最大列表数不能超过1000") private Integer pageNum=10;
}
如下注解:
@Null,标注的属性值必须为空
@NotNull,标注的属性值不能为空
@AssertTrue,标注的属性值必须为true
@AssertFalse,标注的属性值必须为false
@Min,标注的属性值不能小于min中指定的值
@Max,标注的属性值不能大于max中指定的值
@DecimalMin,小数值,同上
@DecimalMax,小数值,同上
@Negative,负数
@NegativeOrZero,0或者负数
@Positive,整数
@PositiveOrZero,0或者整数
@Size,指定字符串长度,注意是长度,有两个值,min以及max,用于指定最小以及最大长度
@Digits,内容必须是数字
@Past,时间必须是过去的时间
@PastOrPresent,过去或者现在的时间
@Future,将来的时间
@FutureOrPresent,将来或者现在的时间
@Pattern,用于指定一个正则表达式
@NotEmpty,字符串内容非空
@NotBlank,字符串内容非空且长度大于0
@Email,邮箱
@Range,用于指定数字,注意是数字的范围,有两个值,min以及max
3.控制器上 加上校验注解@Valid
@PostMapping("save")
public RestResponse save(@RequestBody @Valid QuestionOrderVO questionOrderVO) {
try {
questionOrderService.save(questionOrderVO);
return RestResponse.success("提交成功");
} catch (Exception e) {
log.error("提交失败:{}", e.getMessage());
return RestResponse.fail(e.getMessage());
}
}