Spring提供的一个参数校验框架,使用预定义的注解完成参数校验
1、引入依赖
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>3.2.5</version>
</dependency>
2、在参数前面添加@Pattern注解
@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("用户名已存在!");
}
}
3、在Controller类上添加@Validated注解