【问题标题】:Not getting exception while passing invalid json request body to rest api in spring boot在Spring Boot中将无效的json请求正文传递给rest api时没有出现异常
【发布时间】:2019-06-26 09:41:59
【问题描述】:

我在 spring-boot 中创建了一个 rest API,问题是我将 4 个参数作为请求体参数作为 JSON 对象。

现在,如果我传递带有 5 个参数的 JSON 对象而不是我的 API 仍然调用,则在序列化 JSON 对象时不会发生断言异常。 我有一个带有构造函数的 dto 类,如下所示

public class testDto{
   @NotNull(message = "fistName can not be null.")
   private String fistName;
   @NotNull(message = "lastName can not be null.")
   private String lastName;
   private String nickName;

   public testDto() {
    }

    public testDto(@NotNull(message = "fistName can not be null.") final String fistName ,@NotNull(message = "lastName can not be null.") final String lastName , final String nickName){
      super();
      this.fistName = fistName;
      this.lastName = lastName;
      this.nickName = nickName;
    }
}

我的restapi如下,

@PostMapping(path ={ "/api/v1/user"}, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> saveUser(
            @Valid @RequestBody(required = true) final testDto dto) throws Exception {
}

现在在调用我的 API 时,我正在传递请求正文,如下所示

{
      "fistName" : "abc",
      "lastName" : "xyz",
      "nickName" : "pqr",
      "age" : 25
}

现在,当我传递 age 参数并调用 API 时,我的 API 仍在工作,而不是为 No any constructor found 引发异常,因为我已经过了年龄,它不是我的 dto 类的成员。

预期结果:不允许调用 API 实际结果:允许我调用API

我也尝试过断言异常声明和绑定异常,但没有取得任何成功。

也设置属性

spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

【问题讨论】:

  • 你配置DefaultHandlerExceptionResolver了吗?

标签: java rest spring-boot


【解决方案1】:

Spring Boot 使用 Jackson 将 JSON 有效负载映射到您的 testDto 类的实例。默认情况下,杰克逊是configured to ignore entries in the JSON that it cannot map to the DTO。这遵循 robustness principle 或众所周知的 Postel 定律。

您可以在无法将 JSON 中的条目映射到 DTO 上的属性时将 Jackson 配置为失败,方法是将以下行添加到您的应用程序的 application.properties 文件的 src/main/resources 中:

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

【讨论】:

  • 嗨,安迪,它工作正常,感谢您的快速回复。
【解决方案2】:

当请求是无效的json但是值是正确的ex时怎么办:

{
      "fistName" : "abc",
      "lastName" : "xyz",
      "nickName" : "pqr",
      "nickName" : "pqrs"
}

现在在这种情况下,它使用最后一个并映射它

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 2020-01-30
    • 2016-06-14
    • 2018-02-13
    • 2020-01-02
    • 2016-04-23
    • 2018-09-11
    • 2015-05-23
    相关资源
    最近更新 更多