通过无效的JSON请求主体在Spring Boot中休息API时,没有例外



我已经在Spring-Boot中创建了一个REST API,问题是我将4个参数作为requestbody参数作为JSON对象。

现在,如果我通过5个参数传递了比我的API仍然调用的5个参数,则在序列化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仍在工作,而不是抛出一个异常,因为我已经通过了年龄,而不是我的DTO类成员。

预期结果:不允许致电API实际结果:允许我致电API

我也尝试了具有异常声明和绑定异常,但没有任何成功。

还设置属性

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

Spring Boot使用Jackson将JSON有效载荷映射到您的testDto类的实例。默认情况下,杰克逊(Jackson(被配置为忽略JSON中无法映射到DTO的条目。这遵循鲁棒性原则或邮政定律,也已知。

,当杰克逊无法通过将以下行添加到src/main/resources中的应用程序的application.properties文件:

时,您可以将JSON中的条目映射到DTO上的属性时将其配置为失败。
spring.jackson.deserialization.fail-on-unknown-properties=true

当请求是无效的JSON时该怎么办,但是值是正确的:

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

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

最新更新