Spring HATEOAS构建了分页资源的链接

Вит*_*аев 7 java spring spring-data-rest spring-hateoas spring-boot

我有一个带方法的控制器,它返回PagedResource,如下所示:

@RequestMapping(value = "search/within", method = RequestMethod.POST)
public @ResponseBody PagedResources within(@RequestBody GeoJsonBody body,
                                           Pageable pageable, PersistentEntityResourceAssembler asm) {

    //  GET PAGE

    return pagedResourcesAssembler.toResource(page, asm);
}
Run Code Online (Sandbox Code Playgroud)

现在,我想将该方法添加为根资源的链接,因此我执行以下操作:

public RepositoryLinksResource process(RepositoryLinksResource repositoryLinksResource) {
    repositoryLinksResource.add(linkTo(methodOn(ShipController.class).within(null, null, null)).withRel("within"));

    return repositoryLinksResource;
}
Run Code Online (Sandbox Code Playgroud)

哪个有效,我得到了我的链接,但它添加了没有分页参数的链接.所以它看起来像这样:

    "within": {
        "href": "http://127.0.0.1:5000/search/within"
    },
Run Code Online (Sandbox Code Playgroud)

我想把它变成:

    "within": {
        "href": "http://127.0.0.1:5000/search/within{?page, size}"
    },
Run Code Online (Sandbox Code Playgroud)

在以前的计算器问题表明,固定后GitHub上相应的问题应该是默认的工作,然而,事实并非如此.

我究竟做错了什么 ?

Ind*_*sak 6

使用 PagedResourcesAssembler 自动创建分页链接

我成功地使用了PagedResourcesAssembler. 假设您的实体名为 MyEntity。你的within方法应该返回HttpEntity<PagedResources<MyEntity>>

您的within方法应该类似于下面显示的示例。

@RequestMapping(value = "search/within", method = RequestMethod.POST)
@ResponseBody 
public HttpEntity<PagedResources<MyEntity>> 
    within(@RequestBody GeoJsonBody body,Pageable pageable, 
           PagedResourcesAssembler assembler) {
    //  GET PAGE
    Page<MyEntity> page = callToSomeMethod(pageable);

    return new ResponseEntity<>(assembler.toResource(page), HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)

是一个简单的例子。在此示例中,响应如下所示,

{
    "_embedded": {
    "bookList": [
      {
        "id": "df3372ef-a0a2-4569-982a-78c708d1f609",
        "title": "Tales of Terror",
        "author": "Edgar Allan Poe"
      }
    ]
  },
  "_links": {
    "self": {
      "href": "http://localhost:8080/books?page=0&size=20"
    }
  },
  "page": {
    "size": 20,
    "totalElements": 1,
    "totalPages": 1,
    "number": 0
  }
}
Run Code Online (Sandbox Code Playgroud)

手动创建分页自链接

如果您有兴趣手动创建分页链接,这里是您可以使用的代码片段,

Page<MyEntity> page = callToSomeMethod(pageable);

ControllerLinkBuilder ctrlBldr =
    linkTo(methodOn(ShipController.class).within(body, pageable, asm));
UriComponentsBuilder builder = ctrlBldr.toUriComponentsBuilder();

int pageNumber = page.getPageable().getPageNumber();
int pageSize = page.getPageable().getPageSize();
int maxPageSize = 2000;

builder.replaceQueryParam("page", pageNumber);
builder.replaceQueryParam("size", pageSize <= maxPageSize ? 
    page.getPageable().getPageSize() : maxPageSize);

Link selfLink =
    new Link(new UriTemplate(builder.build().toString()), "self");
Run Code Online (Sandbox Code Playgroud)