我正在使用 Spring Boot (1.4) 开发 REST API,并使用 PagedResourcesAssembler 创建带分页的 JSON 响应,这就像一个魅力。春天的小伙子们干得很棒!
但是,我在提供 URL 查询参数(如果提供)时遇到问题。我知道 PagedResourcesAssembler 无法自行找出 URL 查询参数,因此我想使用 ControllerLinkBuilder.linkTo(controller,parameters) 方法为其提供一个链接:
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public HttpEntity<PagedResources<Document>> find(final DocumentSearch searchForm, final Pageable pageable, final PagedResourcesAssembler assembler) {
final Page<Document> documents = documentService.find(searchForm, pageable);
// this map is just for this example ..
final Map<String, Object> parameters = new HashMap<>();
parameters.put("text", "foobar");
final Link link = ControllerLinkBuilder.linkTo(DocumentController.class, parameters).withSelfRel();
return ResponseEntity.ok(assembler.toResource(documents, link));
}
正如你所看到的,我明确地为链接提供了一个参数,但相应的响应中没有 URL 查询:
{
"_links": {
"first": {
"href": "http://localhost:8080/documents?page=0&size=20"
},
"self": {
"href": "http://localhost:8080/documents"
},
"next": {
"href": "http://localhost:8080/documents?page=1&size=20"
},
"last": {
"href": "http://localhost:8080/documents?page=2&size=20"
}
}
我也尝试调试它,他打电话给:
链接到:123,ControllerLinkBuilder(org.springframework.hateoas.mvc)
展开:152、UriComponents (org.springframework.web.util)
ExpandInternal:47,HierarchicalUriComponents(org.springframework.web.util)
ExpandInternal:330,HierarchicalUriComponents(org.springframework.web.util)
ExpandInternal:340,HierarchicalUriComponents(org.springframework.web.util)直到此时他仍然拥有我的 text=foobar,同时作为 QueryUriTemplateVariable但随后在
ExpandInternal:341,HierarchicalUriComponents(org.springframework.web.util)他不会进入 for 循环,他会/可以将我的 text=foobar 放入他的结果映射中
很感谢任何形式的帮助。
此致,
彼得
UPDATE
为了完成这项工作,我必须做两件事。首先,更改方法签名并添加 @RequestParam 以及我希望在分页链接中作为参数的相应参数,然后使用methodOn from 控制器链接生成器:
public HttpEntity<PagedResources<Document>> find(@RequestParam(value = "text", required = false) final String text, final Pageable pageable, final PagedResourcesAssembler assembler) {
final Link link = ControllerLinkBuilder.linkTo(
ControllerLinkBuilder.methodOn(
DocumentController.class).find(text, pageable, assembler)).withSelfRel();
非常感谢两位的帮助,干杯。
附注有什么方法可以在没有 methodOn 的情况下完成这项工作吗?