Spring HATEOAS构建指向分页资源的链接

时间:2018-07-26 15:46:36

标签: java spring spring-boot spring-data-rest spring-hateoas

我有一个带有方法的控制器,该方法返回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);
}

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

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

    return repositoryLinksResource;
}

哪一个工作正常,我得到了我的链接,但是它添加了没有分页参数的链接。所以看起来像这样:

    "within": {
        "href": "http://127.0.0.1:5000/search/within"
    },

我想把它变成:

    "within": {
        "href": "http://127.0.0.1:5000/search/within{?page, size}"
    },

This上一个关于stackoverflow的问题表明,修复corresponding issue on GitHub后,默认情况下它应该可以工作,但是,不能。

我在做什么错了?

1 个答案:

答案 0 :(得分:3)

使用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);
}

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

{
    "_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
  }
}

手动创建分页自链接

如果您对手动创建分页链接感兴趣,可以使用以下代码段

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");