API返回Long值时如何实现HATEOAS?
创始人
2024-09-07 14:31:05
0

在 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 了。

相关内容

热门资讯

技巧知识分享!德扑ai代打会检... 德扑ai代打会检测到赢率提升策略‌;技巧知识分享!德扑ai代打会检测到(辅助挂)透视辅助(有挂总结)...
透视辅助(wpk安装)外挂透明... 透视辅助(wpk安装)外挂透明挂辅助挂(辅助挂)确实真的有挂(2024新版总结)(哔哩哔哩);玩家在...
一分钟揭秘(wpk安卓)外挂透... 一分钟揭秘(wpk安卓)外挂透明挂辅助机制(辅助挂)德州ai机器人(有挂技巧)-哔哩哔哩;揭秘教程安...
一秒答解!德州ai人工智能软件... 一秒答解!德州ai人工智能软件免费(透视)辅助透视(有挂教学)-哔哩哔哩;亲们利用一分钟了解精致的软...
揭秘关于(fish poker... 【福星临门,好运相随】;揭秘关于(fish poker外挂)外挂透明挂辅助软件(透视)软件透明挂(2...
玩家必看(Wepoke总结)外... WePoke高级策略深度解析‌;玩家必看(Wepoke总结)外挂透明挂辅助挂(透视)的确是真的有挂(...
玩家必看(微扑克线上)外挂透明... 【福星临门,好运相随】;玩家必看(微扑克线上)外挂透明挂辅助器安装(透视)德州ai机器人(确实有挂)...
玩家必备科普!epoker外挂... 玩家必备科普!epoker外挂(辅助挂)透视辅助(有挂详情)-哔哩哔哩;人气非常高,ai更新快且高清...
科普常识(Wepoke教程)外... 科普常识(Wepoke教程)外挂透明挂辅助工具(辅助挂)透视辅助(2025已更新)(哔哩哔哩)1、每...
一分钟揭秘(德扑之星电脑)外挂... 1、一分钟揭秘(德扑之星电脑)外挂透明挂辅助器(透视)原来真的有挂(系统教程)(哔哩哔哩);详细教程...