Try using Custom Annotations to validate the Pageable object. If it is not working, try the argument resolver as shown below.
You can create Argument Resolver in your Spring Configuration that is extending WebMvcConfigurerAdapter
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
PageableHandlerMethodArgumentResolver resolver = new PageableHandlerMethodArgumentResolver() {
@Override
public Pageable resolveArgument(MethodParameter methodParameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
Pageable p = super.resolveArgument(methodParameter, mavContainer, webRequest, binderFactory);
if (webRequest.getParameter("per_page") != null) {
int pageSize = Integer.parseInt(webRequest.getParameter("per_page"));
if (pageSize < 1 || pageSize > 2000) {
message = "Invalid page size";
}
}
if (message != null) {
Set<CustomConstraintViolation> constraintViolations = new HashSet<>();
constraintViolations.add(new CustomConstraintViolationImpl(message));
throw new ConstraintViolationException(constraintViolations);
}
return new PageRequest(p.getPageNumber(), p.getPageSize());
}
};
resolver.setMaxPageSize(2000);
argumentResolvers.add(resolver);
super.addArgumentResolvers(argumentResolvers);
}
This resolver will make sure the max page size is 2000 for every request to your controller.
You need to throw a ConstraintViolationException when the size is more than 2000. For that you need to create a custom ConstraintViolation interface and implement it
public CustomConstraintViolation implements ConstraintViolation<CustomConstraintViolation> {}
public CustomConstraintViolationImpl implements CustomConstraintViolation {
...
}