SpringBoot如何校验请求体额外参数并返回400 Bad Request?
SpringBoot 拒绝请求体中未知字段的实现方案
问题描述
在SpringBoot项目中已实现实体字段的正向校验,现有代码如下:
@Data public class Employee{ @NotNull @NotBlank private String id; @NotNull @NotBlank private String name; } @RestController @Validated class EmployeeController{ @PostMapping(consumes="json", produces="json") public ResponseEntity getEmployee(@Valid @RequestBody Employee employee){ return response; } }
已配置MethodArgumentNotValidException异常处理器,字段校验功能正常。需求为:当请求体包含id、name以外的额外参数(如下示例)时,接口返回400 Bad Request。
示例请求体:
{
"abc":"xyz",
"id":"09e240",
"name":"Billa"
}
实现方案
方案一:针对单个实体类配置拒绝未知字段
在Employee实体类上添加@JsonIgnoreProperties(ignoreUnknown = false)注解,关闭Jackson默认的未知字段忽略行为:
@Data @JsonIgnoreProperties(ignoreUnknown = false) public class Employee{ @NotNull @NotBlank private String id; @NotNull @NotBlank private String name; }
此时请求体包含未知字段时,Jackson会抛出UnrecognizedPropertyException,需要在全局异常处理器中添加该异常的处理逻辑:
@RestControllerAdvice public class GlobalExceptionHandler { // 原有字段校验异常处理 @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) { Map<String, String> errors = new HashMap<>(); ex.getBindingResult().getAllErrors().forEach((error) -> { String fieldName = ((FieldError) error).getField(); String errorMessage = error.getDefaultMessage(); errors.put(fieldName, errorMessage); }); return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); } // 新增未知字段异常处理 @ExceptionHandler(UnrecognizedPropertyException.class) public ResponseEntity<String> handleUnrecognizedPropertyException(UnrecognizedPropertyException ex) { String errorMsg = String.format("请求包含未定义字段:%s", ex.getPropertyName()); return new ResponseEntity<>(errorMsg, HttpStatus.BAD_REQUEST); } }
方案二:全局配置拒绝未知字段
若需要所有接口都拒绝未知字段,可通过配置文件全局设置Jackson的反序列化规则:
- application.properties:
spring.jackson.deserialization.fail-on-unknown-properties=true
- application.yml:
spring: jackson: deserialization: fail-on-unknown-properties: true
此配置会对所有实体类生效,若个别实体类需要允许未知字段,可单独在该类上添加@JsonIgnoreProperties(ignoreUnknown = true)覆盖全局配置,再配合上述异常处理器即可返回400状态码。
内容的提问来源于stack exchange,提问作者Kannan TK
相关产品推荐
相关产品推荐

