繁体   English   中英

Spring REST 响应在自定义控制器中有所不同

[英]Spring REST response is different in a custom controller

我有几个自动创建REST端点的控制器。

@RepositoryRestResource(collectionResourceRel = "books", path = "books")
public interface BooksRepository extends CrudRepository<Books, Integer> {
    public Page<Books> findTopByNameOrderByFilenameDesc(String name);
}

当我访问: http://localhost:8080/Books

我回来了:

{
    "_embedded": {
        "Books": [{
            "id": ,
            "filename": "Test123",
            "name": "test123",
            "_links": {
                "self": {
                    "href": "http://localhost:8080/books/123"
                },
                "Books": {
                    "href": "http://localhost:8080/books/123"
                }
            }
        }]
    },
    "_links": {
        "self": {
            "href": "http://localhost:8080/books"
        },
        "profile": {
            "href": "http://localhost:8080/profile/books"
        },
        "search": {
            "href": "http://localhost:8080/books/search"
        },
        "page": {
            "size": 20,
            "totalElements": 81,
            "totalPages": 5,
            "number": 0
        }
    }
}

当我创建自己的控制器时:

@Controller
@RequestMapping(value = "/CustomBooks")
public class CustomBooksController {
    @Autowired
    public CustomBookService customBookService;

    @RequestMapping("/search")
    @ResponseBody
    public Page<Book> search(@RequestParam(value = "q", required = false) String query,
                                 @PageableDefault(page = 0, size = 20) Pageable pageable) {
        return customBookService.findAll();
    }
}

我会得到一个与自动生成的控制器响应完全不同的响应:

{
    "content": [{
        "filename": "Test123",
        "name" : "test123"
    }],
    "totalPages": 5,
    "totalElements": 81,
    "size": 20,
    "number": 0,
}

我需要做什么才能使我的响应看起来像自动生成的响应? 我想保持一致,所以我不必为不同的响应重写代码。 我应该以不同的方式做吗?


编辑:发现这个: 在 Spring Boot 中为自定义控制器方法启用 HAL 序列化

但我不明白我需要在我的 REST 控制器中更改什么才能启用: PersistentEntityResourceAssembler 我已经在 Google 上搜索PersistentEntityResourceAssembler ,但它一直引导我回到没有太多示例的类似页面(或者示例似乎对我不起作用)。

作为@chrylis建议你应该更换你的@Controller批注与@RepositoryRestController春数据休息调用它的ResourceProcessors定制给定的资源。

为了让您的资源遵循 HATEOAS 规范(如您的 spring-data-rest BooksRepository),您的方法声明返回类型应该类似于HttpEntity<PagedResources<Resource<Books>>>用于将您的 Page 对象转换为 PagedResources:

  • 您需要自动装配这个对象。

    @Autowired private PagedResourcesAssembler<Books> bookAssembler;

  • 你的退货声明应该是这样的

    return new ResponseEntity<>(bookAssembler.toResource(customBookService.findAll()), HttpStatus.OK);

这些更改应该可以帮助您获得包含"_embedded""_links ”属性的 org.springframework.hateoas.Resources 兼容响应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM