第一步:依赖
<!--数据有效性校验-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
第二步:配置文件
@Configuration
public class HibernateValidatorConfig {
@Bean
public static Validator validator() {
return Validation.byProvider(HibernateValidator.class)
.configure()
.failFast(true)
.buildValidatorFactory()
.getValidator();
}
}
第三步:全局异常处理
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResultBean<String> validationErrorHandler(MethodArgumentNotValidException ex) {
List<String> errorInformation = ex.getBindingResult().getAllErrors()
.stream()
.map(ObjectError::getDefaultMessage)
.collect(Collectors.toList());
return ResultBeanUtil.error("").setMsg(errorInformation.toString());
}
}
第四步:
@Getter
@Setter
@ToString
public class AdminLoginDTO {
@NotBlank(message = "账户不能为空")
@Size(min = 6, max = 32)
private String account;
@NotBlank(message = "密码不能为空")
@Size(min = 6, max = 32)
private String password;
}
第五步:
@PostMapping("/v1/login")
public ResultBean<SaTokenInfo> login(@RequestBody @Valid AdminLoginDTO adminLoginDTO) {
}