Spring自动添加' X-Total-Count'标头 [英] Spring auto-add 'X-Total-Count' header

查看:50
本文介绍了Spring自动添加' X-Total-Count'标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using 'admin-on-rest' UI for my Web-application and it has next restriction:

注意:jsonServer REST客户端希望API包含一个对GET_LIST调用的响应中的X-Total-Count标头.该值必须是集合中资源的总数.这允许休息管理员可以知道总共有多少页资源,并建立分页控件.

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标头手动添加到列表返回的REST端点来解决了这个问题,如下所示: response.addHeader("X-Total-Count",String.valueOf(outputList.size()));

I solved the problem by adding X-Total-Count header to my list-returning REST-endpoints manually like this: response.addHeader("X-Total-Count", String.valueOf(outputList.size()));

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

But I'm wondering: if there's some elegant way to do it automatically in Spring? I mean auto-add this header with proper value when some endpoint returns JSON-list?

推荐答案

是的!(如果您使用的是Spring 4.1或更高版本).

Yes, there is! (If you are using spring 4.1 or above).

它称为 ResponseBodyAdvice ,它使您能够拦截呼叫(就在编写响应并允许访问原始http响应之前).

It's called ResponseBodyAdvice and it enables you to intercept calls (just before response is written and gives access to raw http response).

基本上,您需要执行以下控制器建议:

Basically what you need is to implement controller advice like this:

@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;
    }
}

这篇关于Spring自动添加&amp;#39; X-Total-Count&amp;#39;标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆