问题描述
@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;
...
}