根據彈簧HATEOAS guide,資源的列表,每個資源顯示其內容及其鏈接的方式連載分頁時:春HATEOAS:只顯示鏈接,而不序列化的資源/實體
{
"content": [ {
"price": 499.00,
"description": "Apple tablet device",
"name": "iPad",
"links": [ {
"rel": "self",
"href": "http://localhost:8080/product/1"
} ],
"attributes": {
"connector": "socket"
}
}, {
"price": 49.00,
"description": "Dock for iPhone/iPad",
"name": "Dock",
"links": [ {
"rel": "self",
"href": "http://localhost:8080/product/3"
} ],
"attributes": {
"connector": "plug"
}
} ],
"links": [ {
"rel": "product.search",
"href": "http://localhost:8080/product/search"
} ]
}
在大型數據結構的情況下,我認爲(分頁時特別),這將是最好只提供鏈接的資源,而不是資源本身是這樣的:
{
"_links": {
"items": [{
"href": "http://localhost:8080/product/1"
},{
"href": "http://localhost:8080/product/3"
}]
}
}
從事實
除此之外,這將減少轉移的大小rred字節,這也是由HAL specification建議的。目前,我正在做這種方式
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity root(Pageable pageable, final PagedResourcesAssembler<Entity> assembler) {
Page<Entity> entities = entityRepository.findAll(pageable);
PagedResources<Resource> paged = assembler.toResource(entities,
EntityResourceAssembler.getInstance());
Collection<Resource> resources = paged.getContent();
ResourceSupport support = new ResourceSupport();
for (Resource r : resources) {
Link selfLink = r.getLink(Link.REL_SELF);
support.add(new Link(selfLink.getHref(), "items"));
}
return new ResponseEntity<ResourceSupport>(support, HttpStatus.OK);
}
但是,這是一個有點難看,因爲我「手動」需要獲取從資源自身的鏈接。有沒有更好/更聰明的方法來實現我想要的?