Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple requestparam in springboot pageable

i know that this question may be duplicated but i tried a lot with no success

I need to make multiple RequestParam in spring boot rest controller as following :

@GetMapping("/prd-products/test")
@Timed
public ResponseEntity<List<Test>> getAllTests(@RequestParam (required = false) String search, @RequestParam (required = false) Pageable pageable) {
    Page<Test> page = prdProductsService.findAllTest(search, pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/prd-products");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}

when i try to call this service by url like :

http://localhost:9116/api/prd-products/test?search=id==1,id==2&pageable=0&size=2 

it give me following error

"title": "Bad Request",
"status": 400,
"detail": "Failed to convert value of type 'java.lang.String' to required type 'org.springframework.data.domain.Pageable'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'org.springframework.data.domain.Pageable': no matching editors or conversion strategy found",

when i try to send one request param it successfully work .

Note : id==1,id==2 is the way that fields is parsed in search

like image 510
Yousef Al Kahky Avatar asked Jul 28 '26 00:07

Yousef Al Kahky


2 Answers

With Spring Boot you can just register PageableHandlerMethodArgumentResolver bean

@Bean
public PageableHandlerMethodArgumentResolver pageableResolver() {
    return new PageableHandlerMethodArgumentResolver();
}

In controller

public ResponseEntity<List<Test>> getAllTests(
    @RequestParam (required = false) String search,
    @PageableDefault(page = 0, size = 100) Pageable pageable
) {
    ...
}

And then adjust your query parameters to ...&page=0&size=2

like image 87
Nikolai Shevchenko Avatar answered Jul 30 '26 15:07

Nikolai Shevchenko


Spring cannot convert a String to a Pageable. You should create a Pageable object from the request parameters, for example, with PageRequest.of.

Example:

@GetMapping("/prd-products/test")
@Timed
public ResponseEntity<List<Test>> getAllTests(
        @RequestParam (required = false) String search,
        @RequestParam (required = false) Integer pageIndex,
        @RequestParam (required = false) Integer pageSize) {
    Pageable pageable = PageRequest.of(pageIndex, pageSize);
    Page<Test> page = prdProductsService.findAllTest(search, pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/prd-products");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
like image 31
Gustavo Passini Avatar answered Jul 30 '26 17:07

Gustavo Passini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!