【发布时间】:2018-05-23 13:25:38
【问题描述】:
也许这违反了 REST/HAL 原则,但我认为如果我正在查看项目列表,它们不应该包含在 _embedded 标记中。以下是我在 Spring Boot 应用程序中导航到 /characters 时返回的详细信息。
我原以为_embedded 不会出现在characterDescriptions 中,因为它们是页面的主要焦点,是否有可能实现这一点?我应该尝试实现这一目标还是_embedded 成为这里的常态?
在相关说明中,当我使用链接(例如 characters/1)导航到特定资源时,我应该链接回 /characters 父页面还是只在这些页面包含自链接?各种端点(我最终会在这里链接到用户,但这是关于 REST 端点的一般问题)
返回这个 JSON 的控制器方法在 JSON 下面
{
"_embedded": {
"characterDescriptions": [
{
"characterName": "Adrak",
"playerName": "Liam",
"userName": "liam",
"_links": {
"self": {
"href": "http://localhost:8080/characters/1"
}
}
},
{
"characterName": "Thorny",
"playerName": "Aedo",
"userName": "aedo",
"_links": {
"self": {
"href": "http://localhost:8080/characters/2"
}
}
},
{
"characterName": "Anin",
"playerName": "Saoirse",
"userName": "saoirse",
"_links": {
"self": {
"href": "http://localhost:8080/characters/3"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/characters"
}
}
}
下面是相关方法
@GetMapping
public ResponseEntity<Resources<Resource<CharacterDescription>>> getAllCharacterDescriptions( ) {
List <Resource<CharacterDescription>> characters = repository.findAll()
.stream().map( character -> {
Link characterLink = linkTo(methodOn(CharacterDescriptionController.class)
.getCharacterDescription(character.getCharacterId()))
.withSelfRel();
return new Resource<>(character, characterLink);
}).collect(Collectors.toList());
Link allCharacterLink = linkTo(methodOn(CharacterDescriptionController.class)
.getAllCharacterDescriptions(auth))
.withSelfRel();
Resources<Resource<CharacterDescription>> resources = new Resources<>(characters, allCharacterLink);
return ResponseEntity.ok(resources);
}
【问题讨论】:
-
您可以尝试使用@JsonUnwrapped 来注释嵌入式资源,类似于an example,它定义了自己的嵌入式资源支持类
-
没有运气仍然显示为 _embedded
-
这里的页面被认为是一个资源本身,这就是为什么
characterDescriptions在_embeded之下
标签: rest spring-boot spring-hateoas