I am pretty new with Java, and I have just created a spring boot application to practice a bit.
I created a controller that receives a POST request with json:
{
"team1": {
"score": 10,
"colour": "RED"
},
"team2": {
"score": 3,
"colour": "BLUE"
}
}
Controller:
public @ResponseBody
ResponseEntity<Response<Game>> saveGame(
@Valid @RequestBody PostedGameRequest postedGameRequest
) {
// ...
}
The PostedGameRequest gets validated, and that works fine, but there are two properties: team1 and team2 of type PostedGameRequestTeam, and they don't get validated. I added some @NotEmpty attributes in there, but that didn't work.
So now I created a custom TeamValidator, that validates the fields in the Team, but when it fails, it will only show the message that I specified in the @Team attribute class. It would be nice if I could validate each field by itself.
@Builder
public class PostedGameRequest {
@Team()
private final PostedGameRequestTeam team1;
@Team()
private final PostedGameRequestTeam team2;
public PostedGameRequestTeam getTeam1() {
return team1;
}
public PostedGameRequestTeam getTeam2() {
return team2;
}
}
public class TeamValidator implements ConstraintValidator<Team, PostedGameRequestTeam> {
List<String> colours = Arrays.asList("RED","BLUE");
@Override
public boolean isValid(@Valid PostedGameRequestTeam team, ConstraintValidatorContext context) {
if (team == null || team.getColour() == null || team.getScore() == null) {
return false;
}
if (team.getScore() < 0 || team.getScore() > 11) {
// This will only lead to an invalid team message, should get a message about the score in this case
return false;
}
if (!colours.contains(team.getColour())) {
// This will only lead to an invalid team message, should get a message about the colour in this case
return false;
}
return (team.getId() != null || team.getName() != null);
}
}
I have the feeling I am not doing this as I am supposed to do it. Why did my first approach not work? Is there something I have to add that makes the validator also run for the team1 and team2 properties without me adding a custom Validator @Team?