Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing pageable (spring data) in post request

Tags:

java

rest

spring

I have a rest API server which has the following API. I have some other APIs, where i get pageable from GET requests. Here, I need to make a post request for passing the queryDto. So, I cannot pass the page=0?size=20 etc as url parameters.

I would like to know how to pass pageable as JSON object to a POST request

@RequestMapping(value = "/internal/search", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ResponseList<Object> findObjects(@RequestBody QueryDto queryDto, Pageable pageable) {
    if (queryDto.isEmpty()) {
        throw new BadRequestException();
    }

    return someService.findObjectsByQuery(queryDto, pageable);
}
like image 783
Raja Krishnan Avatar asked Jan 20 '16 00:01

Raja Krishnan


2 Answers

sample example

@RequestMapping(path = "/employees",method = RequestMethod.POST,consumes = "application/json",produces = "application/json")
ResponseEntity<Object> getEmployeesByPage(@RequestBody PageDTO page){
    //creating a pagable object with pagenumber and size of the page
    Pageable pageable= PageRequest.of(page.getPage(),page.getSize());
    return ResponseEntity.status(HttpStatus.ACCEPTED).body(employeeRegistryService.getEmployeesByPage(pageable));
}

In your case try to add pagination variables in QueryDTO create a Pageable object and pass it to service

I think that will solve :)

like image 91
ChandraPrakash Avatar answered Oct 04 '22 08:10

ChandraPrakash


I Think that is not possible, at least not already provided by the framework.

The Spring has a HandlerMethodArgumentResolver interface with an implementation called PageableHandlerMethodArgumentResolver that retrieves the request param value calling something like HttpServletRequest.getParameter. So, you can bind the Pageable instance passing the parameters "page" and "size" for GET and POST. So, the following code works:

@RequestMapping(value="/test",method = RequestMethod.POST)
@ResponseBody
public String bindPage(Pageable page){
    return page.toString();
}

$ curl -X POST --data "page=10&size=50" http://localhost:8080/test

Return: Page request [number: 10, size 50, sort: null]

But, if you pass an json nothing happens:

$ curl -X POST --data "{page:10&size:50}" http://localhost:8080/test

Return: Page request [number: 0, size 20, sort: null]

like image 44
Lucas Oliveira Avatar answered Oct 04 '22 06:10

Lucas Oliveira