Spring-如何为我返回的所有响应添加标头? [英] Spring - How can I add a header to ALL responses that I return?

查看:427
本文介绍了Spring-如何为我返回的所有响应添加标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个Spring REST API,该代码在整个代码中都有很多返回.

Lets say I have an Spring REST API which has many, many responses being returned throughout the code.

如果我想在发送的每个响应中都返回两个特定的标头,那么与返回之前手动将其手动添加到每个响应中相比,我该如何以更智能的方式做到这一点?

If I wanted to return two specific headers with every single response I send out, How might I do that in a more intelligent way than manually adding them to every response before returning?

有没有一种机制可以让我在发送响应之前捕获响应并添加标头?

Is there a mechanism which allows me to catch the response before I send it, and add the headers?

供以后的访客问这个问题.这里没有答案实际上不会导致拦截器正常工作.我建议去别的地方.

EDIT : For future visitors asking this question. None of the answers here will actually result in a working interceptor. I suggest looking elsewhere.

推荐答案

正确的答案是使用过滤器.拦截器对此并不正确,无论网上有人怎么说.拦截器无法正常工作.

The correct answer is to use a filter. Interceptors are not correct for this, regardless what people online say. Interceptors just don't work as desired.

有效的解决方案是创建一个过滤器,如下所示:

Working solution is to create a filter as follows :

public class myAwesomeFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                HttpServletResponse response, FilterChain filterChain)  throws ServletException, IOException {

        response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.addHeader("pragma", "no-cache");
        filterChain.doFilter(request, response);
    }
}

然后,在web.xml中-您需要满足以下条件:

Then, in web.xml - you need the following :

<filter>
    <filter-name>sensitiveFormHeaderFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

这篇关于Spring-如何为我返回的所有响应添加标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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