I have the following controller code
@GetMapping("/users")
public ResponseEntity<UserDto> getUsers(Filter filter) {
return ResponseEntity.ok(userService.findUsers(filter));
}
Filter.java:
public class Filter {
private Integer page;
private Integer size;
private String sort;
... lots of other parameters
}
The request parameters are written as a Java object to avoid adding lots of parameters to controller. However, all of the parameters are made optional by Spring. What I want is to have some parameters like page
and size
required, but others like sort
optional. If I had them as controller parameters, I could use @RequestParam(required = true/false)
. Is it possible to do something similar in Java class?
You can use the javax.validation API to specify some constraints on the fields of a class.
In your case you could use @NotNull
and @NotEmpty
according to your requirements and the field types such as :
import javax.validation.constraints.NotNull;
import javax.validation.constraints.NotEmpty;
...
public class Filter {
@NotNull
private Integer page;
@NotEmpty
private Integer size;
private String sort;
... lots of other parameters
}
Then specify the @Valid
annotation for the parameter you want to validate :
import javax.validation.Valid;
...
@GetMapping("/users")
public ResponseEntity<UserDto> getUsers(@Valid Filter filter) {
return ResponseEntity.ok(userService.findUsers(filter));
}
If the filter parameter doesn't respect the constraints, a ConstraintViolationException
is thrown that you can leave or catch to map it to a specific client 4XX error by using a Spring exception handler such as @ControllerAdvice
.