1、SpringBoot集成hibernate-validate模块,实现校验
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2、使用校验注解
@Data
@ApiModel("封装注册请求数据")
public class UserRegisterDto {// @NotNull 校验参数不为null// @NotEmpty 不能为null以及空字符串@NotEmpty(message = "用户名不能为空")private String userName;@NotNull(message = "密码不能为空")@Length(min = 6,max = 10,message = "密码必须6-10位")private String pwd;@NotNull(message = "手机号不能为空")@Pattern(regexp = "^1[3456789]\\d{9}$",message = "手机号码不合法")private String phone;
}
3、控制器方法启用校验
@RestController
@RequestMapping("/user")
public class UserController {/*** 用户注册*/@PostMapping("/regist")public Result regist(@RequestBody @Valid UserRegisterDtouserRegisterDto){return Result.ok();}
}
快速失败:当校验只要有一个参数不合法,立刻返回失败,不再继续校验。
@Configuration
public class ValidatorConfiguration {@Beanpublic Validator validator(AutowireCapableBeanFactoryspringFactory) {try (ValidatorFactory factory =Validation.byProvider(HibernateValidator.class).configure()
// 快速失败.failFast(true)
// 解决 SpringBoot 依赖注入问题.constraintValidatorFactory(newSpringConstraintValidatorFactory(springFactory)).buildValidatorFactory()) {return factory.getValidator();}}
}