问题描述
我正在尝试将以下代码用于 REST API
@GetMapping(produces = { "application/hal+json" },value = "/topics")
public CollectionModel<Topic> getAllTopics() {
List<Topic> topics= topicService.getTopicList();
for (Topic topic : topics) {
String topicId = topic.getId();
Link selfLink = linkTo(TopicController.class).slash(topicId).withSelfRel();
topic.add(selfLink);
}
Link link = linkTo(TopicController.class).withSelfRel();
CollectionModel<Topic> result = CollectionModel.of(topics,link);
return result;
}
我得到的输出低于
{
"_embedded": {
"topicList": [
{
"id": "2","name": "rest api1","description": "REST API1","_links": {
"self": {
"href": "http://localhost:8080/2"
}
}
}
]
},"_links": {
"self": {
"href": "http://localhost:8080"
}
}
}
预期网址应为
{
"_embedded": {
"topicList": [
{
"id": "2","_links": {
"self": {
"href": "http://localhost:8080/topics/2"
}
}
}
]
},"_links": {
"self": {
"href": "http://localhost:8080/topics"
}
}
}
解决方法
修改
Link link = linkTo(TopicController.class).withSelfRel();
到
Link link = linkTo(methodOn(TopicController.class).getAllTopics()).withSelfRel();