如何使用WebClient使用Spring Hateoas CollectionModel?
我弄清楚了如何使用EntityModel,但到目前为止我还无法使用CollectionModel(Spring代码使用Groovy) 我的班级:如何使用WebClient使用Spring Hateoas CollectionModel?,spring,webclient,hateoas,Spring,Webclient,Hateoas,我弄清楚了如何使用EntityModel,但到目前为止我还无法使用CollectionModel(Spring代码使用Groovy) 我的班级: @Relation(value = "person", collectionRelation = "people") class Person { long id String firstName String lastName } 我的控制器: CollectionModel<Person&
@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
}在上发帖并获得一些见解后,我能够让它正常工作。注意,这是在使用Groovy
首先,在控制器中,我确保产品设置为hal:
@RequestMapping(method = RequestMethod.GET, produces = "application/hal+json")
CollectionModel<Person> getPeople() {
Link link = linkTo(PersonController).withSelfRel()
List<EntityModel> entityModelList = [this.getPerson()]
}
然后在调用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>>>() {})
}
}
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
}
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 })