我正在尝试覆盖API的默认GET Verb,以添加更具体的细节。
我创建了一个restController和一个Get requestMapping:
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Resources<User>> getUsers(Pageable pageable) {
Page<User> users = userReposiotry.findAll(pageable);
Resources<User> userResources = new Resources<>(users);
return new ResponseEntity<Resources<User>>(userResources, HttpStatus.OK);
}
它运行良好,但它不会返回链接和其他额外信息,如果不被覆盖则可用。
自定义返回:
{
"_embedded": {
"users": [
{
"id": 1,
"username": "admin",
"registrationDate": "2015-11-18T21:04:54.000+0000",
"name": "Admin",
"email": "admin@admin.com",
"enabled": true,
"dateOfBirth": "2015-11-18",
"imageIdentifier": null,
"confirmationKey": ""
}]
}
}
原来:
{
"_embedded": {
"users": [
{
"id": 1,
"username": "admin",
"registrationDate": "2015-11-18T21:04:54.000+0000",
"name": "Admin",
"email": "admin@admin.com",
"enabled": true,
"dateOfBirth": "2015-11-18",
"imageIdentifier": null,
"confirmationKey": "",
"_links": {
"self": [
{
"href": "http://localhost:8080/api/users/1"
},
{
"href": "http://localhost:8080/api/users"
}
],
"user": {
"href": "http://localhost:8080/api/users/1{?projection}",
"templated": true
},
"inviteToApps": {
"href": "http://localhost:8080/api/users/1/inviteToApps"
},
"userRoles": {
"href": "http://localhost:8080/api/users/1/userRoles"
},
"currencyTokens": {
"href": "http://localhost:8080/api/users/1/currencyTokens"
},
"workoutAttendees": {
"href": "http://localhost:8080/api/users/1/workoutAttendees"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/api/users"
},
"profile": {
"href": "http://localhost:8080/api/profile/users"
},
"search": {
"href": "http://localhost:8080/api/users/search"
}
},
"page": {
"size": 20,
"totalElements": 7,
"totalPages": 1,
"number": 0
}
}
如何在原始内容中添加与自定义关系的关系?
答案 0 :(得分:2)
只需返回自定义Bean,Map等,而不是ResponseEntity:
@ResponseBody
@RequestMapping(method = RequestMethod.GET)
public Object getUsers(Pageable pageable) {
Page<User> users = userReposiotry.findAll(pageable);
Resources<User> userResources = new Resources<>(users);
List<MyCustomUser> customUsers = [...]
return customUSers;
}
// "some more specific details" in MyCustomUser
public class MyCustomUser extends User{
private List<Links> links;
// TODO: constructor, getter, setter.
}
答案 1 :(得分:0)
那是因为你返回的是实体,而不是资源。试试这个:
public ResponseEntity<Resources<Resource<User>>> getUsers(Pageable pageable) {
Page<User> users = userReposiotry.findAll(pageable);
Resources<Resource<User>> userResources = Resources.wrap(users);