gpt4 book ai didi

java - Spring 自动添加 'X-Total-Count' header

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:01:02 24 4
gpt4 key购买 nike

我正在为我的 Web 应用程序使用“admin-on-rest”UI,它有下一个限制:

Note: The jsonServer REST client expects the API to include a X-Total-Count header in the response to GET_LIST calls. The value must be the total number of resources in the collection. This allows admin-on-rest to know how many pages of resources there are in total, and build the pagination controls.

我通过手动将 X-Total-Count header 添加到我的列表返回 REST 端点来解决问题,如下所示:response.addHeader("X-Total-Count", String.valueOf(outputList.size()));

但我想知道:是否有一些优雅的方法可以在 Spring 中自动执行此操作?我的意思是当某些端点返回 JSON 列表时自动添加具有适当值的 header ?

最佳答案

是的,有! (如果您使用的是 spring 4.1 或更高版本)。

它叫做 ResponseBodyAdvice它使您能够拦截调用(就在写入响应之前并提供对原始 http 响应的访问权限)。

基本上你需要的是像这样实现 Controller 建议:

@ControllerAdvice
public class ResourceSizeAdvice implements ResponseBodyAdvice<Collection<?>> {

@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
//Checks if this advice is applicable.
//In this case it applies to any endpoint which returns a collection.
return Collection.class.isAssignableFrom(returnType.getParameterType());
}

@Override
public Collection<?> beforeBodyWrite(Collection<?> body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
response.getHeaders().add("X-Total-Count", String.valueOf(body.size()));
return body;
}
}

关于java - Spring 自动添加 'X-Total-Count' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44375435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com