英文:
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(int foo) {
this.foo = foo;
}
public int getFoo() {
return this.foo;
}
}
现在,我期望当我使用{}
作为请求体向/endpoint
发出请求时,它会返回状态码400,但我却得到了状态码200和body.foo
的值是0。
我该如何确保{}
的请求体被拒绝?
英文:
I have the following post method handler:
@PostMapping("/endpoint")
public int myEndpoint(@RequestBody MyBody body) {
return body.foo;
}
Which accepts the following request body:
class MyBody {
private int foo;
public MyBody() {}
public MyBody(foo) {
this.foo = foo;
}
public getFoo() {
return this.foo;
}
}
Now, I expect that when I make request to /endpoint
with body {}
It'll return status 400,
but I get 200 and body.foo
is 0.
How can I make sure {}
body is rejected?
答案1
得分: 1
您可以使用注解验证请求体:
```java
@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;
...
}
英文:
You could validate the body with annotations :
@PostMapping("/endpoint")
public int myEndpoint(@RequestBody @Valid MyBody body) {
return body.foo;
}
you also need to add validations dependencie
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
then MyBody
is a DTO, don't use primitive types as int since they have a default value. Add the validations you need :
class MyBody {
@NotNull
private Integer foo;
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论