【问题标题】:do not allow {} as request body不允许 {} 作为请求正文
【发布时间】:2020-12-03 16:30:17
【问题描述】:

我有以下 post 方法处理程序:

@PostMapping("/endpoint")
public int myEndpoint(@RequestBody MyBody body) {
    return body.foo;
}

接受以下请求正文:

class MyBody {
    private int foo;

    public MyBody() {}

    public MyBody(foo) {
        this.foo = foo;
    }

    public getFoo() {
        return this.foo;
    }
}

现在,我希望当我使用正文 {}/endpoint 发出请求时,它会返回状态 400,

但我得到 200 而body.foo 是 0。

如何确保{} 正文被拒绝?

【问题讨论】:

  • 首先,将int 等原始值更改为Integer。其次,您可以使用@Airy 所说的验证或使用Optional
  • 为什么投反对票?

标签: java json spring-boot http-post jackson-databind


【解决方案1】:

您可以使用注释验证正文:

@PostMapping("/endpoint")
public int myEndpoint(@RequestBody @Valid MyBody body) {
    return body.foo;
}

你还需要添加验证依赖

<dependency> 
        <groupId>org.springframework.boot</groupId> 
        <artifactId>spring-boot-starter-validation</artifactId> 
</dependency>

那么MyBody 是一个DTO,不要使用原始类型作为int,因为它们有一个默认值。添加您需要的验证:

class MyBody {
    @NotNull
    private Integer foo;

    ...
}

【讨论】:

  • body 参数前的@NotNull 是多余的。它不会影响任何东西,默认情况下需要@RequestBody anonation=true。
猜你喜欢
  • 1970-01-01
  • 2017-03-15
  • 2013-11-22
  • 2015-03-09
  • 2023-03-10
  • 2018-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多