I have a Spring Controller with a DTO PlacePixelRequest
as the request body in POST
request:
@RestController
public class CanvasController {
@PostMapping("/canvas/pixel")
public void placePixel(@Valid @RequestBody final PlacePixelRequest placePixelRequest) {
try {
canvasManager.placePixel(placePixelRequest);
} catch (PixelOutOfBoundsException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Coordinates requested are out of bounds");
}
}
}
import javax.validation.constraints.NotNull;
@Data
@ToString
public class PlacePixelRequest {
@NotNull
private int x;
@NotNull
private int y;
@NotNull
private PixelColor pixelColor;
@NotNull
private String placedBy;
}
I have put @NotNull
on each of the fields, however, requests are going through just fine even without specifying these fields in the request body:
curl --location 'http://localhost:8080/canvas/pixel' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer <TOKEN>' \
--data '{
"x": "0",
"y": "5"
}'
returns 200 OK
.
I have tried looking at different solutions where the suggestion is to check if the @Valid
annotation is present on the controller method request body, which is already present in my case.
The other suggestion was to have the validation API on classpath. I already have these two dependencies in my pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
If you use spring 3+ you should use this packages.
import jakarta.validation.Valid
import jakarta.validation.constraints.Max
import jakarta.validation.constraints.Min
import jakarta.validation.constraints.NotNull
Take a loot at realese notes from Spring Boot 3 - they changed a lot)