Spring Boot 中使用 JSR 对前端传来的数据进行校验的过程。
本文省略对返回结果和响应枚举类型的封装。
导入包
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
|
在 spring-boot-starter-web 中已包含上述包。
统一异常处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @Slf4j @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public JSONResult<Void> handlerValidationException(MethodArgumentNotValidException e) { log.warn("参数校验失败:" + e.getMessage(), e); String errorMessage = e.getBindingResult() .getAllErrors() .stream() .map(ObjectError::getDefaultMessage) .collect(Collectors.joining(";")); return JSONResult.error(StatusCodeEnum.FAIL.getCode(), errorMessage); }
}
|
JSR 注解校验
UserVO
1 2 3 4 5
| @Data public class UserVO { @NotNull(message = "用户名不能为空") private String username; }
|
Controller
1 2 3 4 5 6
| @PostMapping(value="/save")
public JSONResult insert(@RequestBody @Valid UserVO vo){ userService.insert(vo); return JSONResult.success(); }
|
接收到前端发送请求后会对数据进行校验,如果校验失败会抛出 MethodArgumentNotValidException 异常,全局异常处理器将捕获到异常进行处理。
测试
当前端请求:
后端返回:
1 2 3 4
| { "code": 400, "message": "用户名不能为空" }
|