Reputation:
I'm using spring boot to build API, in post request I use Valid notation to validate user input that is posted as JSON file, however when I test it by leaving some fields empty they are still passed. I'm not sure why since I'm using valid notation before the object argument.
what can be wrong?
Object class
@NotNull(message = "Please provide a name")
private String name;
@NotNull(message = "Please provide a gender")
private Gender gender;
@NotNull(message = "Please provide a birthDay")
private String birthDay;
@NotNull(message = "Please provide a latitude")
private double latitude;
@NotNull(message = "Please provide a longitude")
private double longitude;
public Wolf(String id, @NotNull String name, @NotNull Gender gender, @NotNull String birthDay, @NotNull double latitude, @NotNull double longitude)
{
this.id = id!=null ? id : UUID.randomUUID().toString();
this.name= name;
this.gender= gender;
this.birthDay= birthDay;
this.latitude= latitude;
this.longitude= longitude;
}
rest-controller class
@Autowired
private Wolf_Service wolf_service;
@RequestMapping("Wolf/wolf_list")
public List<Wolf> All_wolfs()
{
return wolf_service.display_wolf_list();
}
@PostMapping(value = "Wolf/createwolf", consumes = "application/json", produces = "application/json")
public Wolf createwolf (@Valid @RequestBody Wolf wolf) {
var isAdded = wolf_service.add_wolf(wolf);
if (!isAdded) {
return null;
}
return wolf;
}
Upvotes: 0
Views: 2531
Reputation: 283
Check that you import correctly from Validation.Constraints not from com.sun.istack.
import javax.validation.constraints.NotNull;
If that not fix your problem. Check your pom.xml, if you have used validation dependency.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Upvotes: 0
Reputation: 2724
This issue often comes in latest version of spring boot(2.3.0).
You would need to add the below dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Note : You can use hibernate-validator
instead of spring-boot-starter-validation
.
Upvotes: 2
Reputation: 29
It depends on how you are handling your null values. If i.e. leaving a String field empty means you will send "" this will be passed as it is not a null value, hence the @NotNull annotation on your Wolf class does not apply.
Michael
Upvotes: 0