简体   繁体   English

如何使用Spring-Hateoas以HAL格式获取响应

[英]How to get a response in HAL-Format with Spring-Hateoas

Basically i have the same issue like the member who posted this question 基本上我有像发布此问题的成员一样的问题

When i request a single user in my Application, i get the response in the HAL-format, like i wish 当我在我的应用程序中请求单个用户时,我得到了HAL格式的响应,就像我希望的那样

http://localhost:8080/api/v1/users/25 with GET : http:// localhost:8080 / api / v1 / users / 25 with GET

{
"userId": "25",
"firstname": "Beytullah",
"lastname": "Güneyli",
"username": "gueneylb",
"_links": {
"self": {
  "href": "http://localhost:8080/api/v1/users/25"
 },
"roles": [
  {
    "href": "http://localhost:8080/api/v1/roles/33"
  },
  {
    "href": "http://localhost:8080/api/v1/roles/34"
  }
 ]
 }
 }

But, when i request all users , i get the response in non-HAL-Format, like this: 但是,当我请求所有用户时,我得到非HAL格式的响应,如下所示:

http://localhost:8080/api/v1/users with GET : http:// localhost:8080 / api / v1 / GET 用户

[...

{
"userId": "25",
"firstname": "Beytullah",
"lastname": "Güneyli",
"username": "gueneylb",
"links": [
  {
    "rel": "self",
    "href": "http://localhost:8080/api/v1/users/25"
  },
  {
    "rel": "roles",
    "href": "http://localhost:8080/api/v1/roles/33"
  },
  {
    "rel": "roles",
    "href": "http://localhost:8080/api/v1/roles/34"
  }
]
},

...]

Here are my methods: 这是我的方法:

@RequestMapping(value = "users", method = RequestMethod.GET, produces = MediaTypes.HAL_JSON_VALUE)
public List<UserResource> list() throws MyException, NotFoundException {
    List<User> userList= userRepository.findAll();
    List<UserResource> resources = new ArrayList<UserResource>();
    for (User user : userList) {
        resources.add(getUserResource(user));
    }
    if(userList == null)
        throw new MyException("List is empty");
    else
        return resources;
}

@RequestMapping(value = "users/{id}", method = RequestMethod.GET)
public UserResource get(@PathVariable Long id) throws NotFoundException {

    User findOne = userRepository.findOne(id);
    if (findOne == null){
        log.error("Unexpected error, User with ID " + id + " not found");
        throw new NotFoundException("User with ID " + id + " not found");
    }
    return getUserResource(findOne);
}

private UserResource getUserResource(User user) throws NotFoundException {
    resource.add(linkTo(UserController.class).slash("users").slash(user.getId()).withSelfRel());
    for(Role role : user.getRoles()){
          resource.add(linkTo(RoleController.class).slash("roles").slash(role.getId()).withRel("roles"));
    }
    return resource;

}

You can see that both methods invoke the getUserResource(User user) method. 您可以看到两个方法都调用getUserResource(User user)方法。

But when i get all users in my database, the format of the _links is not like i want. 但是当我在我的数据库中获得所有用户时, _links的格式不是我想要的。 I think it must be something about the List of resources i return. 我认为它必须是我返回的资源List Maybe because of that it has no HAL-Format. 也许是因为它没有HAL格式。 I also tried a Set instead of List but it gave me the same response 我也尝试过Set而不是List但是它给了我相同的响应

You should return Resources<UserResource> in your list() method. 您应该在list()方法中返回Resources<UserResource>

return new Resources(resources);

You could also add a self-link to the resources itself to point to the list resource. 您还可以向资源本身添加自我链接以指向列表资源。

Furthermore, I would suggest using a RessourceAssembler to create the resource instance - see http://docs.spring.io/spring-hateoas/docs/0.23.0.RELEASE/reference/html/#fundamentals.resource-assembler . 此外,我建议使用RessourceAssembler来创建资源实例 - 请参阅http://docs.spring.io/spring-hateoas/docs/0.23.0.RELEASE/reference/html/#fundamentals.resource-assembler

Additionally, you could add paging to your list resource. 此外,您可以向列表资源添加分页。 For this you need to: 为此,您需要:

  • use the findAll method in your repository that returns a Page<User> . 在存储库中使用findAll方法返回Page<User>
  • autowire PagedResourcesAssembler<User> in your controller 在控制器中自动装配PagedResourcesAssembler<User>
  • return PagedResources<UserResource> in your list method 在list方法中返回PagedResources<UserResource>
  • use the PagedResourcesAssembler to convert the Page into PagedResources 使用PagedResourcesAssemblerPage转换为PagedResources

This would result in something like this: 这将导致类似这样的事情:

    private final PagedResourcesAssembler<User> pagedResourcesAssembler;

    @RequestMapping(value = "users", method = RequestMethod.GET)
    public ResponseEntity<PagedResources<UserResource>> list(Pageable pageable) {
        final Page<User> page = repository.findAll(pageable);
        final Link link = ControllerLinkBuilder.linkTo(ControllerLinkBuilder.methodOn(this.getClass()).list(null)).withSelfRel();

        PagedResources<UserResource> resources = page.getContent().isEmpty() ?
                (PagedResources<UserResource>) pagedResourcesAssembler.toEmptyResource(page, ShippingZoneResource.class, link)
                : pagedResourcesAssembler.toResource(page, resourceAssembler, link);

        return ResponseEntity.ok(resources);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM