Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate size of Pageable?

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?

like image 263
Jin Kwon Avatar asked Nov 24 '17 07:11

Jin Kwon


People also ask

Which are the valid option to create Pageable instance?

The most common way to create a Pageable instance is to use the PageRequest implementation: Pageable pageable = PageRequest.

What is Pageable unpaged ()?

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)

What is Pageable?

Adjective. pageable (not comparable) That can be paged. (computer science, of computer memory) That accepts paging.

What is Pageable in Java?

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.


1 Answers

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();
    }
}
like image 118
Manoj Avatar answered Sep 26 '22 04:09

Manoj