Reputation: 7524
I have defined a rest endpoint method as:
@GetMapping("/get")
public ResponseEntity getObject(@Valid MyObject myObject){....}
This maps request parameters to MyObject.
MyObject is defined as(with lombok, javax.validation annotations):
@Value
@AllArgsConstructor
public class MyObject {
@Min(-180) @Max(180)
private double x;
@Min(-90) @Max(90)
private double y;
}
But validations are not working. Even with values out of prescribed range, request doesn't throw error and goes well.
Upvotes: 6
Views: 6530
Reputation: 21
I just had to add the following dependency to get the validations working.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Upvotes: 1
Reputation: 920
If you on a version of Spring Boot > 2.3 it now states
Validation Starter no longer included in web starters
... you’ll need to add the starter yourself.
i.e.
For Maven builds, you can do that with the following:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
For Gradle, you will need to add something like this:
dependencies {
...
implementation 'org.springframework.boot:spring-boot-starter-validation'
}
Please refer to https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#validation-starter-no-longer-included-in-web-starters
Upvotes: 8
Reputation: 2429
Annotate your controller with org.springframework.validation.annotation.Validated
Upvotes: 3
Reputation: 1045
I see a couple of things here that you should fix. Let's start talking about the REST standard, the first rule is to think in endpoints as representation of resources, not operations, for example, in your code, I presume the MyObject
class represents a Point (you should refactor the class to have a proper name), then the path value for the getObject
can be "/point". The operations are mapped on the HTTP method, accordingly:
In getObject
you're expecting to receive an object. The get method according to the REST standards means you want to retrieve some data, and usually you send some data included in the url like ../app-context/get/{id}, here the id is a parameter that tells your controller you want some info belonging to an id, so if you would invoke the endpoint like as ../app-context/get/1 to get info of some domain object identified by the number 1.
If you want to send data to the server, the most common HTTP method is a POST.
According to this, at design level you should:
getObject
.getObject
representing a resource.At code level, with the above comments, you could change this as:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MyObject {
@Min(-180) @Max(180)
private double x;
@Min(-90) @Max(90)
private double y;
}
@PostMapping("/point")
public ResponseEntity savePoint(@RequestBody @Valid MyObject myObject) {...}
I will explain the changes:
Upvotes: 1