首页 > 解决方案 > 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吗?

标签: spring-bootspring-hateoas

解决方案


利用.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()是获取方法映射不是强制性部分的方法。


推荐阅读