在Springboot 2.2.4上将HAL与Hateoas一起使用

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

我有一个扩展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"
            }
        ]
    },...
spring-boot spring-hateoas
1个回答
0
投票

我只是注意到我没有退还正确的东西。我返回列表,而不是CollectionModel

public CollectionModel<AddressRestResponseModel> getUserAddresses(@PathVariable String userKeyId) {
    // same code 
    return new CollectionModel<>(returnValue);
}
© www.soinside.com 2019 - 2024. All rights reserved.