I'm using org.springframework.data.domain.Pageable with my @RestController
.
How can I validate or limit the page size?
Without any validation, when clients call with size
of 10000
. The actual pageSize
is 2000
.
This could lead wrong signal for last page, I think.
How can I validate it and notify clients about it? Say with 400
?
The most common way to create a Pageable instance is to use the PageRequest implementation: Pageable pageable = PageRequest.
unpaged() . means that invoking repository. findAll(Pageable. unpaged()) should load all entities. What actually happens is that the response contains only 10 result with paging information (total pages, ect)
Adjective. pageable (not comparable) That can be paged. (computer science, of computer memory) That accepts paging.
The Pageable implementation represents a set of pages to be printed. The Pageable object returns the total number of pages in the set as well as the PageFormat and Printable for a specified page. See Also: PageFormat , Printable.
You can write a custom annotation to validate Pageable
object
@Constraint(validatedBy = PageableValidator.class)
@Target( { ElementType.METHOD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface PageableConstraint {
String message() default "Invalid pagination";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int maxPerPage() default 100;;
}
and Its implementation
public class PageableValidator implements
ConstraintValidator<PageableConstraint, Pageable> {
private int maxPerPage;
@Override
public void initialize(PageableConstraint constraintAnnotation) {
maxPerPage=constraintAnnotation.maxPerPage();
}
@Override
public boolean isValid(Pageable value, ConstraintValidatorContext context) {
return value.getPageSize()<=maxPerPage;
}
}
and you can use it over your controller like any other javax validation annotations.
@RestController
@RequestMapping("/api")
@Validated
public class EmployeeRestController {
@Autowired
private EmployeeService employeeService;
@GetMapping("/employees")
public List<Employee> getAllEmployees(@PageableConstraint(message = "Invalid page size",maxPerPage = 400) Pageable pageable) {
return employeeService.getAllEmployees();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With