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?
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;
...
}