在 API 的返回值中添加链接,以便客户端可以动态地通过链接访问相关资源。可以将 Long 值作为链接的一部分,以确保每个链接都是唯一的。
代码示例:
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/{id}")
public ResponseEntity getResourceById(@PathVariable Long id) {
MyResource myResource = new MyResource(id);
// 添加 HATEOAS 链接
Link selfLink = linkTo(methodOn(MyController.class).getResourceById(id)).withSelfRel();
Link parentLink = linkTo(methodOn(MyController.class).getParentResource(id)).withRel("parent");
myResource.add(selfLink);
myResource.add(parentLink);
return ResponseEntity.ok(myResource);
}
@GetMapping("/{id}/parent")
public ResponseEntity getParentResource(@PathVariable Long id) {
MyResource parentResource = new MyResource(id);
// 添加 HATEOAS 链接
Link selfLink = linkTo(methodOn(MyController.class).getParentResource(id)).withSelfRel();
Link childLink = linkTo(methodOn(MyController.class).getResourceById(id)).withRel("child");
parentResource.add(selfLink);
parentResource.add(childLink);
return ResponseEntity.ok(parentResource);
}
}
在上述示例中,MyResource
是资源类,它继承自 ResourceSupport
,可以通过 add()
方法添加链接。在 getResourceById()
和 getParentResource()
方法中,分别添加了 self 和 parent、child 链接,并将 Long 值作为链接的一部分。这样客户端就可以通过访问链接来实现 HATEOAS 了。