Spring hateoas:在链接上添加确切的值

问题描述 投票:0回答:1

我想为列表中返回的任何对象返回一个自我引用,所以我这样做:

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-boot spring-hateoas
1个回答
0
投票

使用.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()是获取方法映射的一种方法,不是必需的部分。

© www.soinside.com 2019 - 2024. All rights reserved.