依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
查看LocalValidatorFactoryBean类的源码,发现默认的ValidationMessageSource(校验出错时的提示文件)是resources目录下的ValidationMessages.properties文件,因此在resources目录下创建ValidationMessages.properties文件
user.name.size=用户名长度介于5到10个字符之间
user.address.NotEmpty=用户地址不能为空NotEmpty
user.age.size=年龄输入不正确
user.email.notnull=邮箱不能为空notnull
user.email.pattern=邮箱格式不正确
创建User类,配置数据校验:
@Data public class User2 { private Integer id; @AssertFalse(groups = ValidationGroup2.class) private Boolean enabled; @PastOrPresent(groups = ValidationGroup2.class) private Year birthday; @Size(min = 5, max = 10, message = "{user.name.size}", groups = ValidationGroup1.class) private String name; @NotEmpty(message = "{user.address.NotEmpty}", groups = ValidationGroup2.class) private String address; @Min(value = 1, message = "{user.age.size}", groups = ValidationGroup2.class) @DecimalMax(value = "200", message = "{user.age.size}") @Digits(integer = 3,fraction = 3,groups = ValidationGroup2.class) @NegativeOrZero(groups = ValidationGroup2.class) private Integer age; @Email(message = "{user.email.pattern}") @NotNull(message = "{user.email.notnull}", groups = {ValidationGroup1.class, ValidationGroup2.class}) private String email; }
配置完成后,接下来创建UserController:
@RestController @RequestMapping("/valid") public class UserValidatedController { /** * 给User参数添加@Validated注解,表示需要对该参数做校验,紧接着的BindingResult参数表示在校验出错时保存的出错信息 * * @param user user * @param result 在校验出错时保存的出错信息 * @return 出错信息 */ @PostMapping("/user") // public List<String> addUser(@Validated @RequestBody User2 user, BindingResult result) { public List<String> addUser(@Validated(ValidationGroup2.class) @RequestBody User2 user, BindingResult result) { List<String> errors = new ArrayList<>(); // 如果BindingResult中的hasErrors方法返回true,表示有错误信息,此时遍历错误信息,将之返回给前端。 if (result.hasErrors()) { List<ObjectError> allErrors = result.getAllErrors(); for (ObjectError error : allErrors) { errors.add(error.getDefaultMessage()); } } return errors; } @PostMapping("/user2") public void user2(@Validated(ValidationGroup2.class) @RequestBody User2 user) { } }
分组校验:
public interface ValidationGroup1 { } public interface ValidationGroup2 { }
校验注解:
全域异常捕获:
@ControllerAdvice @Slf4j public class GlobalExceptionHandler { //post请求参数校验抛出的异常 @ExceptionHandler(value = MethodArgumentNotValidException.class) @ResponseBody public Response methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) { /*//获取异常中随机一个异常信息 FieldError fieldError = e.getBindingResult().getFieldError(); return Response.buildFailure(fieldError.getCode(), fieldError.getDefaultMessage());*/ return getResponse(e.getBindingResult(), e); } //get请求参数校验抛出的异常 @ExceptionHandler(BindException.class) @ResponseBody public Response bindExceptionHandler(BindException e) { /*//获取异常中随机一个异常信息 FieldError fieldError = e.getBindingResult().getFieldError(); return Response.buildFailure(fieldError.getCode(), fieldError.getDefaultMessage());*/ return getResponse(e.getBindingResult(), e); } private Response getResponse(BindingResult bindingResult, Exception e) { List<String> errors = new ArrayList<>(); if (bindingResult.hasErrors()) { List<ObjectError> allErrors = bindingResult.getAllErrors(); for (ObjectError error : allErrors) { errors.add(error.getDefaultMessage()); } } List<String> stringList = errors.stream().sorted().collect(Collectors.toList());// 排序 return Response.buildFailure("", stringList.toString()); } }