本文介绍了如何在Spring Boot REST API中启用对JSON/Jackson @RequestBody的严格验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在JSON请求中指定了额外的参数,如何引发错误?例如,"xxx"不是有效的参数,也不是@RequestBody对象中的参数.

How do I throw an error if extra parameters are specified in the JSON request? For example, "xxx" is not a valid parameter or in the @RequestBody object.

我尝试将@Validated添加到界面中,但没有帮助.

I tried adding @Validated to the interface, but it didn't help.

@RequestMapping(value = "/api/v2/stats", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<DataResponse> stats(Principal principal, @Validated @RequestBody ApiParams apiParams) throws ApiException;

我想启用一个严格"模式,以便如果请求中存在多余的虚假参数,它将给出一个错误.我找不到办法.我找到了确保有效参数确实存在的方法,但是没有办法确保没有多余的参数.

I would like to enable a 'strict' mode so that it will give an error if extra, spurious parameters exist in the request. I could find no way to do this. I found ways to ensure the valid parameters do exist, but no way to ensure there are not extra parameters.

public class ApiParams extends Keyable {

    @ApiModelProperty(notes = "email of user", required = true)
    String email;


public abstract class Keyable {

    @ApiModelProperty(notes = "API key", required = true)
    @NotNull
    String apiKey;

Spring Boot 1.5.20

Spring Boot 1.5.20

推荐答案

在后台,Spring使用Jackson库将POJO序列化/反序列化为JSON,反之亦然.默认情况下,框架用于执行此任务的ObjectMapperFAIL_ON_UNKNOWN_PROPERTIES设置为false.

Behind the scene, Spring uses the Jackson library to serialize/deserialize POJO to JSON and vice versa. By default, the ObjectMapper that the framework uses to perform this task has its FAIL_ON_UNKNOWN_PROPERTIES set to false.

您可以通过在application.properties中设置以下配置值来在全局上启用此功能.

You can turn this feature on GLOBALLY by setting the following config value in application.properties.

spring.jackson.deserialization.fail-on-unknown-properties=true

或者,如果使用YAML格式,请将以下内容添加到您的application.yaml(或.yml)文件中):

Or if using YAML format, add the following to your application.yaml (or .yml) file):

spring:
  jackson:
    deserialization:
      fail-on-unknown-properties: true

随后,如果要忽略特定POJO的未知属性,则可以在该POJO类中使用注释@JsonIgnoreProperties(ignoreUnknown=true).

Subsequently, if you want to ignore unknown properties for specific POJO, you can use the annotation @JsonIgnoreProperties(ignoreUnknown=true) in that POJO class.

仍然,这可能意味着需要大量的手工工作.从技术上讲,忽略那些意外数据不会违反任何软件开发原则.在某些情况下,您的@Controller前面可能有一个过滤器或servlet,它在做一些其他的事情,而您可能不知道哪些需要这些额外的数据.看来值得付出努力吗?

Still, this could mean a lot of manual work going forward. Technically, ignoring those unexpected data doesn't violate any software development principles. There might be scenarios where there's a filter or servlet sitting in front of your @Controller doing additional stuff that you're not aware of which requires those extra data. Does it seem worth the effort?

这篇关于如何在Spring Boot REST API中启用对JSON/Jackson @RequestBody的严格验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 03:02