【问题标题】:How to consume Spring Hateoas CollectionModel using WebClient?如何使用 WebClient 使用 Spring Hateoas CollectionModel?
【发布时间】:2020-11-16 19:00:28
【问题描述】:

我知道如何使用 EntityModel,但目前无法使用 CollectionModel(Spring 代码使用 Groovy)

我的班级:

@Relation(value = "person", collectionRelation = "people")
class Person {
  long id
  String firstName
  String lastName
}

我的控制器:

CollectionModel<Person> getPeople() {
    Person person = new Person(
            id: 2L,
            firstName: 'Mark',
            lastName: 'Hamil'
    )
    Collection<Person> people = Collections.singleton(person)
    CollectionModel.of(people)
  }

然后我创建了一个服务来消费控制器的输出:

CollectionModel<Person> model= this.webClient.get().uri('localhost:8080/api/people')
                  .retrieve()
                  .bodyToMono(new TypeReferences.CollectionModelType<Person>())
                  .block()

          List<Person> people = model.content

但是模型是空白的。我不确定我做错了什么。

这是 localhost:8080/api/people 的原始输出

{
"_embedded": {
    "people": [
        {
            "id": 2,
            "firstName": "Mark",
            "lastName": "Hamil"
        }
    ]
}

}

【问题讨论】:

    标签: spring webclient hateoas


    【解决方案1】:

    https://gitter.im/spring-projects/spring-hateoas# 发帖并获得一些见解后,我能够得到这个工作。请注意,这是使用 Groovy。

    首先,在控制器中,我确保将产品设置为 hal:

        @RequestMapping(method = RequestMethod.GET, produces = "application/hal+json")
        CollectionModel<Person> getPeople() {
           Link link = linkTo(PersonController).withSelfRel()
           List<EntityModel> entityModelList = [this.getPerson()]
        }
    

    this.getPerson() 在哪里:

    EntityModel<Person> getPerson() {
        Person person = new Person(
          id: 2L,
          firstName: 'Mark',
          lastName: 'Hamil'
        )
        Link link = linkTo(PersonController).slash(person.id).withSelfRel()
        EntityModel<Person> personEntityModel = EntityModel.of(person, link)
    
        personEntityModel
      }
    

    然后在调用api中:

        Mono<CollectionModel<EntityModel<Person>>> personCollectionModel = this.webClient
           .get()
           .uri('localhost:8080/uswf-api/people')
           .accept(MediaTypes.HAL_JSON)
           .exchange()
           .flatMap { response ->
               if (response.statusCode().isError()) {
                  System.out.println('Error')
            } else {
              response.bodyToMono(new ParameterizedTypeReference<CollectionModel<EntityModel<Person>>>() {})
            }
        }
    

    然后我可以通过订阅结果来使用这个结果:

    personCollectionModel.subscribe( { collectionModel -> collectionModel.content })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-03
      • 2019-06-21
      • 1970-01-01
      • 1970-01-01
      • 2015-03-22
      • 2018-07-23
      • 2017-10-25
      相关资源
      最近更新 更多