java Spring - 如何为我返回的所有响应添加标头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43481539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring - How can I add a header to ALL responses that I return?
提问by IWishIWasABarista
Lets say I have an Spring REST API which has many, many responses being returned throughout the code.
假设我有一个 Spring REST API,它在整个代码中返回了许多响应。
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.
编辑:对于将来提出此问题的访问者。这里的任何答案实际上都不会导致有效的拦截器。我建议寻找其他地方。
回答by IWishIWasABarista
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);
}
}
Then, in web.xml - you need the following :
然后,在 web.xml - 您需要以下内容:
<filter>
<filter-name>sensitiveFormHeaderFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
回答by AllanT
The way I got it to work was using ResponseBodyAdvice as shown in the examplelinked by Faxy.
我让它工作的方式是使用 ResponseBodyAdvice ,如Faxy链接的示例所示。
Here is my solution for adding cache-control headers to every request:
这是我为每个请求添加缓存控制标头的解决方案:
@ControllerAdvice
public class HeaderModifierAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(final MethodParameter returnType, final Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(final Object body,
final MethodParameter returnType,
final MediaType selectedContentType,
final Class<? extends HttpMessageConverter<?>> selectedConverterType,
final ServerHttpRequest request,
final ServerHttpResponse response) {
response.getHeaders().add("Cache-Control", "no-cache, no-store, must-revalidate");
response.getHeaders().add("Pragma", "no-cache");
response.getHeaders().add("Expires", "0");
return body;
}
}
回答by Moshe Arad
You can easily do those using Handler Interceptors which allow you to modify the request processing lifecycle within Spring MVC. Interceptors are a very powerful tool that allows us to add functionality to the request processing lifecycle at 3 different points:
您可以使用 Handler Interceptors 轻松完成这些操作,它允许您修改 Spring MVC 中的请求处理生命周期。拦截器是一个非常强大的工具,它允许我们在 3 个不同的点向请求处理生命周期添加功能:
- before a controller handles a request
- after a controller method completed its code execution
- when the view is about to be rendered and sent back as the response to the client
- 在控制器处理请求之前
- 在控制器方法完成其代码执行后
- 当视图即将被渲染并作为对客户端的响应发回时
I think option 2 will suit your needs.
我认为选项 2 将满足您的需求。
Then you can write something like this:
然后你可以这样写:
public class MyInterceptor extends HandlerInterceptorAdapter {
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
//add your two headers on the response here
}
}
step 2 is to register that interceptor in your configuration file, add the next lines to your XML configuration:
第 2 步是在您的配置文件中注册该拦截器,将下一行添加到您的 XML 配置中:
<mvc:interceptors>
<bean Class="your interceptor class">
</mvc:interceptors>
from now on that interceptor will apply for every request.
从现在开始,拦截器将应用于每个请求。
回答by Ivan Kurinnyi
You may use spring interceptorsfor this purpose. Or there is more generic way to do this which not requires Spring for this. It's filter