1、添加依赖
org.springframework.boot
spring-boot-starter-validation
2、验证器类
public class UserStorevalidator {
private Long userId;
@NotNull(message = "用户名不能为空")
@Size(min = 2, max = 20, message = "账号长度必须是2-20个字符")
private String userName;
@Size(min = 6, max = 20, message = "密码长度必须是6-20个字符")
private String userPassword;
@NotNull(message = "用户类型不能为空")
private Character type;
private Timestamp registerTime;
}
3、在控制器中使用
@PostMapping("")
public ReturnResult store(@RequestBody @Validated UserStorevalidator userStorevalidator) {
UserStorevalidator store = userService.store(userStorevalidator);
System.out.println(userStorevalidator);
return ReturnResult.success( "添加用户成功");
}
4、自定义验证失败的异常
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleBindGetException(MethodArgumentNotValidException ex) {
// 获取所有异常
// List errors = ex.getBindingResult()
// .getFieldErrors()
// .stream()
// .map(x -> x.getDefaultMessage())
// .collect(Collectors.toList());
return "验证失败啦";
}



