Spring Boot 如果RequestBody中存在任何未知字段,则需要拒绝POST/PUT请求

5n0oy7gb  于 2022-11-23  发布在  Spring
关注(0)|答案(1)|浏览(87)

@有效性检查正在对各个字段进行。如果POST/PUT请求的JSON请求体中存在未知字段,是否有任何方法可以拒绝请求?下面是我的示例DTO类和控制器。对于下面的示例请求体(例如),请求应该被拒绝/抛出异常。如果有任何帮助或建议,将不胜感激。

{
"accountid" : "P12345",
"name" : "Cardiology",
"domain" : "Apollo"
}

public class Account {

    @NotEmpty(message = "accountid is required")
    private String accountid;

    @NotEmpty(message = "name is required")
    private String name;

   //getters & setters

}

**********************************************************************************************

public class BeanController {

    @PostMapping(path = "/accounts")
    public ResponseEntity<?> getAllAccounts(@RequestBody @Valid Account account) {

        System.out.println("::: Account is " + account + " :::");

        return ResponseEntity.ok().body("SUCCESS");

    }
}
bvhaajcl

bvhaajcl1#

您可以使用@JsonIgnoreProperties来执行此操作。

@JsonIgnoreProperties(ignoreUnknown = false)
public class Account {

    @NotEmpty(message = "accountid is required")
    private String accountid;

    @NotEmpty(message = "name is required")
    private String name;

   //getters & setters

}

在application.yml中添加以下属性,以便在最新版本的spring-boot中工作。

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

相关问题