在springboot中,@Validated可对后台接收model进行数据校验,不符合则抛出异常。
使用场景:
1、在model中进行声明规则
@Data
public class UserVo {
@NotBlank(message = "用户名不能为空")
private String username;
@Size(min = 5 ,max = 20)
private String realname;
}
2、在controller层的方法形参前进行声明
/**
* @Title: insert
* @Description: 新增记录
* @param orgVo
* @return
*/
@PostMapping
public Result insert(@RequestBody @Validated UserVo userVo) {
int i = userService.insert(userVo);
return ResultGenerator.genOkResult(i);
}
常用注解:
@AssertFalse 校验false
@AssertTrue 校验true
@DecimalMax(value=,inclusive=) 小于等于value,inclusive=true,是小于等于
@DecimalMin(value=,inclusive=) 与上类似
@Max(value=) 小于等于value
@Min(value=) 大于等于value
@NotNull 检查Null
@Past 检查日期
@Pattern(regex=,flag=) 正则
@Size(min=, max=) 字符串,集合,map限制大小
@Validate 对po实体类进行校验(若modelA中存在modelB,可使用@Validate声明modelB进行校验,具体校验规则在modelB进行声明)