一、引入Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
二、在登录注册时的参数校验,也可将@Pattern添加到实体类对应的属性,并在controller类或者在实体类传参时添加@Validated
@Validated
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/register")
public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password){
User u = userService.findByUserName(username);
if(u == null){
userService.register(username, password);
return Result.success();
}else{
return Result.error("用户名已被占用");
}
}
}
三、分组校验的应用场景
(1)分组校验
把校验项进行归类分组,在完成不同功能的时候,校验指定组中的校验项。
(2)分组校验步骤
1、定义分组
2、定义校验项时指定归属的分组
3、校验时指定要校验的分组
(3)为什么要用分组校验
当进行根据id进行update修改操作时,需要给实体类中id加@NotNull注解;但加上之后进行插入insert操作时,因为在数据库中主键id设置了自增,insert时不需要指定id即为空,校验不能通过,insert操作不能成功。所以要分成添加组校验和修改组校验进行约束校验。
(4)实例
给id指明groups分组时,@NotNull只对update分组起效
public class Category {
@NotNull(groups = Update.class)
private Integer id;//主键ID
@NotEmpty
private String categoryName;//分类名称
@NotEmpty
private String categoryAlias;//分类别名
private Integer createUser;//创建人ID
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;//创建时间
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateTime;//更新时间
public interface Update extends Default {
}
}
如果说某个校验项没有指定分组, 默认属于Default分组。分组之间可以继承, A extends B,那么A中拥有B的所有校验项。使用@Validated注解使实体类参数校验起效。
@PutMapping
public Result update(@RequestBody @Validated(Category.Update.class) Category category){
categoryService.update(category);
return Result.success();
}