【发布时间】:2023-03-18 06:45:01
【问题描述】:
基本上我和发布这个question的成员有同样的问题
当我在我的应用程序中请求单个用户时,我会得到 HAL 格式的响应,就像我希望的那样
http://localhost:8080/api/v1/users/25 与 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"
}
]
}
}
但是,当我请求所有用户时,我会得到非 HAL 格式的响应,如下所示:
http://localhost:8080/api/v1/users 与 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"
}
]
},
...]
这是我的方法:
@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;
}
您可以看到这两个方法都调用了getUserResource(User user) 方法。
但是当我在我的数据库中获取所有用户时,_links 的格式不是我想要的。我认为这一定与我返回的资源的List 有关。也许正因为如此,它没有 HAL 格式。我也尝试了 Set 而不是 List 但它给了我相同的响应
【问题讨论】:
标签: java spring-boot spring-hateoas hypermedia