I have the following controller methods:
@RequestMapping(method = GET, produces = APPLICATION_JSON_VALUE)
@Transactional(readOnly = true)
public ResponseEntity list(Pageable pageable, PagedResourcesAssembler pagedResourcesAssembler) {
Page<Customer> customers = customerRepository.findAll(pageable);
return ResponseEntity.ok().body(pagedResourcesAssembler.toResource(customers, customerResourceAssembler));
}
@RequestMapping(value = "/search", method = GET, produces = APPLICATION_JSON_VALUE)
@Transactional(readOnly = true)
public ResponseEntity search(@RequestParam("q") String q, Pageable pageable, PagedResourcesAssembler pagedResourcesAssembler) {
Specification spec = where(..some specs..);
Page<Customer> customers = customerRepository.findAll(spec, pageable);
return ResponseEntity.ok().body(pagedResourcesAssembler.toResource(customers, customerResourceAssembler));
}
The first method returns all customer resources as pages.
The second one also returns paged results but has the option to provide a q
query parameter to filter.
The JSON HATEOAS response from the search method contains a next page link like:
{
"rel": "next",
"href": "http://localhost:8080/api/customers/search?page=1&size=10{&sort}"
}
The problem is here the q
query parameter is lost.
Should I use the PagedResourcesAssembler
differently here?
I think I found the solution by creating a link manually; see example below.
@RequestMapping(value = "/search", method = GET, produces = APPLICATION_JSON_VALUE)
@Transactional(readOnly = true)
public ResponseEntity search(@RequestParam("q") String q, Pageable pageable, PagedResourcesAssembler pagedResourcesAssembler) {
// create link to search method with q; pass link as 3th param to paged resource assembler's toResource method
Link link = linkTo(methodOn(CustomerController.class).search(q, pageable, pagedResourcesAssembler)).withSelfRel();
Specification spec = where(..some specs..);
Page<Customer> customers = customerRepository.findAll(spec, pageable);
return ResponseEntity.ok().body(pagedResourcesAssembler.toResource(customers, customerResourceAssembler, link));
}
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