依赖
- 注解
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
</dependency>
- 校验支持,包含以上依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
定义校验条件和消息
代码语言:javascript复制public class MyDTO {
@NotBlank(message = "ID不能为空")
private String id;
}
指定需要校验的参数
代码语言:javascript复制@RestController
public class MyController {
@PostMapping("/api/execute")
public void execute(
@Valid @RequestBody MyDTO mydto
) {}
}
效果
代码语言:javascript复制{"timestamp":"2021-12-08T08:21:34.000000786","status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MethodArgumentNotValidException","message":"Validation failed for object='MyDTO'. Error count: 1","path":"/api/execute"}
异常消息处理
代码语言:javascript复制import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
@ControllerAdvice
@RestController
public class MethodArgumentNotValidExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
public Error onException(MethodArgumentNotValidException e) {
List<FieldError> fieldErrors = e.getFieldErrors();
List<String> messages = fieldErrors.stream().map(FieldError::getDefaultMessage).collect(Collectors.toList());
String message = StringUtils.join(messages, ";");
List<ErrorDetails> errors = fieldErrors.stream().map(
fieldError -> new ErrorDetails(
fieldError.getObjectName(),
fieldError.getField(),
fieldError.getCode(),
fieldError.getDefaultMessage()
)
).collect(Collectors.toList());
return new Error(message, errors);
}
@Data
static class Error {
private final String exception = MethodArgumentNotValidException.class.getSimpleName();
private final String message;
private final List<ErrorDetails> errors;
}
@Data
static class ErrorDetails {
private final String objectName;
private final String field;
private final String code;
private final String message;
}
}
注: 如果不以@RestController注解,消息将以404状态响应返回
效果2
代码语言:javascript复制{"exception":"MethodArgumentNotValidException","message":"ID不能为空","errors":[{"objectName":"mydto","field":"id","code":"NotBlank","message":"ID不能为空"}]}