Spring Boot 参数校验
kecho

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 {
// 处理 @Valid 校验失败异常
@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")
// 接口接收参数上添加 @Valid 注解进行校验
public JSONResult insert(@RequestBody @Valid UserVO vo){
userService.insert(vo);
return JSONResult.success();
}

接收到前端发送请求后会对数据进行校验,如果校验失败会抛出 MethodArgumentNotValidException 异常,全局异常处理器将捕获到异常进行处理。

测试

当前端请求:

1
2
3
{
"username": ""
}

后端返回:

1
2
3
4
{
"code": 400,
"message": "用户名不能为空"
}