基本上我都喜歡誰張貼這question如何獲得在HAL-格式與Spring-HATEOAS響應
,當我在我的應用程序請求單個用戶的成員同樣的問題,我得到的HAL響應-format,就像我希望
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
,但它給了我相同的迴應
謝謝你爲你的非常詳細和有益的答案!我發現了另一個解決這個問題的方法。我將'@EnableHypermediaSupport(type = {HypermediaType.HAL})'註釋添加到我的控制器類中,並且它工作正常。但我喜歡你的建議,並會使用它。現在我將看看你建議的這種分頁方式。非常感謝你 :) –