spring – 如何将自定义查询参数添加到分页hateoas结果中的下一个/上一个链接?
作者:互联网
我有以下控制器方法:
@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,spring-data-jpa,spring-data,spring-hateoas 来源: https://codeday.me/bug/20190824/1712861.html