不允许{}作为请求正文

问题描述

我有以下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。

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

解决方法

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

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

    ...
}