spring-hateoasspring-data-commons

Generate links with additional query parameters using PagedResourcesAssembler


I'm using spring-data-common's PagedResourcesAssembler in my REST controller, and I was happy to see it even generates next/previous links in the response. However, in those cases where I have additional query parameters (besides page, size, sort), these are not included in the generated links. Can I somehow configure the assembler to include the parameters in the links?

Many thanks, Daniel


Solution

  • You need to build base link by yourself and pass it to "toResource" method of PagedResourcesAssembler.

    @Controller
    @RequestMapping(value = "/offer")
    public class OfferController {
    
        private final OfferService offerService;
    
        private final OfferAssembler offerAssembler;
    
        @Autowired
        public OfferController(final OfferService offerService, OfferAssembler offerAssembler) {
    
            this.offerService= checkNotNull(offerService);
            this.offerAssembler= checkNotNull(offerAssembler);
        }
    
        @RequestMapping(value = "/search/findById", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
        public ResponseEntity<PagedResources<OfferResource>> findOfferById(
                @RequestParam(value = "offerId") long offerId, Pageable pageable,
                PagedResourcesAssembler<OfferDetails> pagedResourcesAssembler) {
            Page<OfferDetails> page = service.findById(offerId, pageable);
    
            Link link = linkTo(methodOn(OfferController.class).findOfferById(offerId,
                    pageable,
                    pagedResourcesAssembler)).withSelfRel();
            PagedResources<OfferResource> resource = pagedResourcesAssembler.toResource(page, assembler, link);
            return new ResponseEntity<>(resource, HttpStatus.OK);
        }
    }
    

    As a result you will get:

    http://[your host]/[your app context]/offer/search/findById?offerId=[some offer id]{&page,size,sort}