gpt4 book ai didi

spring - 如何将自定义查询参数添加到分页 hatoas 结果中的下一个/上一个链接?

转载 作者:行者123 更新时间:2023-12-02 06:37:44 24 4
gpt4 key购买 nike

我有以下 Controller 方法:

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

第一个方法将所有客户资源作为页面返回。

第二个也返回分页结果,但可以选择提供 q 查询参数进行过滤。

搜索方法的 JSON HATEOAS 响应包含下一页链接,例如:

{
"rel": "next",
"href": "http://localhost:8080/api/customers/search?page=1&size=10{&sort}"
}

问题在于 q 查询参数丢失。

我应该在这里以不同的方式使用PagedResourcesAssembler吗?

最佳答案

我想我通过手动创建链接找到了解决方案;请参阅下面的示例。

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

关于spring - 如何将自定义查询参数添加到分页 hatoas 结果中的下一个/上一个链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26919619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com