我有一个扩展RepresentationModel的模型响应:
@Getter @Setter
public class AddressRestResponseModel extends RepresentationModel<AddressRestResponseModel> {
private String addressKeyId;
private String city;
private String country;
private String streetName;
private String zipCode;
}
我还有一个使用HateOAS的控制器,应该返回hal + json:
@GetMapping(
path="/{userKeyId}/addresses",
produces = {
MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE,
"application/hal+json"
}
)
public List<AddressRestResponseModel> getUserAddresses(@PathVariable String userKeyId) {
List<AddressRestResponseModel> returnValue = new ArrayList<>();
List<AddressDto> addressDtos = addressService.getAddresses(userKeyId);
if (addressDtos != null && !addressDtos.isEmpty()) {
ModelMapper modelMapper = new ModelMapper();
Type listType = new TypeToken<List<AddressRestResponseModel>>() {}.getType();
returnValue = modelMapper.map(addressDtos, listType);
for (AddressRestResponseModel address: returnValue) {
Link addressLink = linkTo(methodOn(UserController.class).getUserAddress(userKeyId, address.getAddressKeyId())).withSelfRel();
address.add(addressLink);
Link userLink = linkTo(methodOn(UserController.class).getUser(userKeyId)).withRel("user");
address.add(userLink);
}
}
return returnValue;
}
我还为仇恨症添加了pom依赖项:
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-hateoas -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
<version>2.2.4.RELEASE</version>
</dependency>
我在邮递员中尝试了此入口点,并将接受标头设置为“ application / hal + json”。我应该收到类似“ _links”和其中的对象的东西:
不幸的是,我没有hal格式,看起来好像没有使用此格式:
[
{
"addressKeyId": "0eLoiLVfuAmNIPdUH8rZSGFntYGnRF",
"city": "Somewhere",
"country": "Somewhere",
"streetName": "123, mystreet",
"zipCode": "12345F",
"links": [
{
"rel": "self",
"href": "http://localhost:8080/appws/users/MxQp8LEUYCELQzmvVx9RpLtWOH1bIY/addresses/0eLoiLVfuAmNIPdUH8rZSGFntYGnRF"
},
{
"rel": "user",
"href": "http://localhost:8080/appws/users/MxQp8LEUYCELQzmvVx9RpLtWOH1bIY"
}
]
},...
答案 0 :(得分:0)
我只是注意到我没有退还正确的东西。我返回List而不是CollectionModel
public CollectionModel<AddressRestResponseModel> getUserAddresses(@PathVariable String userKeyId) {
// same code
return new CollectionModel<>(returnValue);
}