5

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

非常感谢,丹尼尔

4

2 回答 2

7

您需要自己构建基本链接并将其传递给 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}
于 2014-10-30T11:27:39.673 回答
2

以下解决方案基于@palisade 提供的答案,但解决了分页参数未出现在自我链接中的问题——这个问题由答案的两位评论者指出,我自己也经历过。

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

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": [
        {
            ...
于 2019-06-10T23:57:48.180 回答