问题描述
我有一个使用 Spring Data Rest 构建的 REST API 服务,但在某些特定情况下,我需要一个自定义控制器和服务逻辑。现在我需要生成一个 HAL 响应,类似于我使用 Spring Data Rest 默认得到的响应。
这是代码。
控制器
@RestController
@RequiredArgsConstructor
public class Controller {
private final ConfigService configService;
private final HALGenerator halGenerator;
private final ControllerHelper helper;
@GetMapping(value = "/configs")
public ResponseEntity<Object> getConfigs(@RequestHeader Map<String,String> headers,@AuthContext AuthInfo authInfo,Pageable pageable
) {
String orgId = helper.getOrgIdFromHeader(authInfo);
Page<ConfigEntity> configsByOrgId = configService.getConfigsByOrgId(orgId,pageable);
List<EntityModel<ConfigEntity>> entity = configsByOrgId
.getContent()
.stream()
.map(p -> halGenerator.generateLinks(p,p.getConfigId()))
.collect(Collectors.toList());
CollectionModel<EntityModel<ConfigEntity>> configs = halGenerator.getCollectionAndSearchLinks(entity,ConfigEntity.class,pageable);
return ResponseEntity.ok().body(configs);
}
}
HAL 代码生成器
@Component
@RequiredArgsConstructor
@Slf4j
public class HALGenerator {
private final RepositoryEntityLinks entityLinks;
public <T> EntityModel<T> generateLinks(T entity,Object id) {
EntityModel<T> resource = EntityModel.of(entity);
resource.add(entityLinks.linkToItemResource(entity.getClass(),id).withSelfRel());
resource.add(entityLinks.linkToCollectionResource(entity.getClass()));
resource.add(entityLinks.linksToSearchResources(entity.getClass()));
return resource;
}
public <T> CollectionModel<EntityModel<T>> getCollectionAndSearchLinks(List<EntityModel<T>> entity,Class<T> tClass,Pageable pageable) {
CollectionModel<EntityModel<T>> resource = CollectionModel.of(entity);
resource.add(entityLinks.linkToCollectionResource(tClass));
resource.add(entityLinks.linksToSearchResources(tClass));
return resource;
}
}
回复:当前回复
{
"_embedded": {
"configs": [
{
"id": 988,"configId": 988,"userId": 45679,"name": "config2","remarks": "remarks1","_links": {
"self": {
"href": "http://localhost:8080/configs/988"
},"configs": {
"href": "http://localhost:8080/configs{?page,size,sort}","templated": true
}
}
},{
"id": 995,"configId": 995,"name": "config"
"remarks": "remarks1","_links": {
"self": {
"href": "http://localhost:8080/configs/995"
},"templated": true
}
}
}
]
},"_links": {
"configs": {
"href": "http://localhost:8080/configs{?page,"templated": true
},"findByName": {
"href": "http://localhost:8080/configs/search/findByName{?name}","templated": true
}
}
}
预期响应:
{
"_embedded": {
"configs": [
{
"id": 988,"templated": true
}
},"page": {
"size": 2,"totalElements": 84,"totalPages": 42,"number": 0
}
}
所有响应和结构都符合预期,但页面细节不知何故丢失。
请提出实现此目标的任何方法。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)