spring-boot - Spring hatoas:在链接上添加确切的值
问题描述
我想为我在列表中返回的任何对象返回一个自我引用,所以我这样做:
for(PetModel pet : pets){
pet.add(linkTo(methodOn(PetController.class).getPetById(pet.getId())).withSelfRel());
}
这给了我:
{
"links": [
{
"rel": "self",
"href": "http://localhost:8080/pet/{petId}"
}
],
"id": 1,
难道不能改为http://localhost:8080/pet/1吗?
解决方案
利用.slash(pet.getId())
Link link = ControllerLinkBuilder
.linkTo(PetController.class)
.slash(pet.getId())
.withSelfRel();
//Add link to singular resource
pet.add(link);
解释:
- 该
linkTo()
方法检查 PetController 类并获取其根映射 - 该
slash()
方法将petId值添加为链接的路径变量 - 最后,将
withSelfMethod()
关系限定为自链接
通过methodOn()
在代理控制器上虚拟调用目标方法来获得方法映射。methodOn()
是获取方法映射不是强制性部分的方法。
推荐阅读
- ruby-on-rails - 如何拥有与显示名称具有不同参数值的字段
- node.js - 使用节点 js 进行 SSL 连接
- composer-php - 安装最新的作曲家依赖
- r - “pROC”包的“coords”函数返回与“caret”包的“confusionMatrix”函数不同的敏感性和特异性值
- python - 如何有效地理解文档稀疏的框架?
- python-3.x - 如何转换数据并计算 TFIDF 值?
- javascript - jQuery:动画完成后执行
- mysql - MySQL:构建多个 mysql 选择的问题
- java - 从依赖于第一个的 3 个下拉列表中选择项目
- openstreetmap - Openstreetmap 的使用政策限制