使用PagedResourcesAssembler生成带有其他查询参数的链接

时间:2014-09-03 19:02:39

标签: spring-hateoas spring-data-commons

我在我的REST控制器中使用了spring-data-common的PagedResourcesAssembler,我很高兴看到它甚至在响应中生成了下一个/上一个链接。但是,在我有其他查询参数(除了页面,大小,排序)的情况下,这些参数不包含在生成的链接中。我能以某种方式配置汇编程序以在链接中包含参数吗?

非常感谢, 丹尼尔

2 个答案:

答案 0 :(得分:6)

您需要自己构建基本链接并将其传递给PagedResourcesAssembler的“toResource”方法。

@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);
    }
}

结果你会得到:

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

答案 1 :(得分:0)

以下解决方案基于@palisade提供的答案,但是解决了分页参数未出现在self链接中的问题-由两个答案的评论者指出的问题,我自己也遇到了。

通过替换木栅栏的链接声明...

Link link = linkTo(methodOn(OfferController.class).findOfferById(offerId,
                pageable,
                pagedResourcesAssembler)).withSelfRel();

...具有以下内容...

Link link = new Link(ServletUriComponentsBuilder.fromCurrentRequest().build()
               .toUriString())
               .withSelfRel();

...我正在获得如下所示的页面链接:

{
    "links": [
        {
            "rel": "first",
            "href": "http://[your host]/[your app context]/offer/search/findById?offerId=[some offer id]&page=0&size=1"
        },
        {
            "rel": "prev",
            "href": "http://[your host]/[your app context]/offer/search/findById?offerId=[some offer id]&page=2&size=1"
        },
        {
            "rel": "self",
            "href": "http://[your host]/[your app context]/offer/search/findById?offerId=[some offer id]&page=3&size=1"
        },
        {
            "rel": "next",
            "href": "http://[your host]/[your app context]/offer/search/findById?offerId=[some offer id]&page=4&size=1"
        },
        {
            "rel": "last",
            "href": "http://[your host]/[your app context]/offer/search/findById?offerId=[some offer id]&page=6&size=1"
        }
    ],
    "content": [
        {
            ...