不允许 {} 作为请求主体

do not allow {} as request body

我有以下 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 发送正文 {} 请求时,它会 return 状态 400,

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

如何确保 {} body 被拒绝?

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

@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;

    ...
}