在过滤器中添加响应头? [英] Adding header in response in filter?
问题描述
我需要在每个响应中添加标头.我打算在下面做
I need to add the header in each response. I am planning to do below
public class MyFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
filterChain.doFilter(request, response);
response.addHeader("Access-Control-Allow-Origin", "*");
}
}
我想在 filterChain.doFilter(request, response)
之后做,这样一旦控制器处理它,我只需在返回前添加标题给客户.正确吗?
I would like to do it after filterChain.doFilter(request, response)
so that once controller process it, i just add header before returning
to client. Is it correct ?
但根据如何编写响应过滤器?
chain.doFilter
返回后,再做任何事情都为时已晚响应.此时,整个响应已经发送到客户端,而您的代码无权访问它.
After
chain.doFilter
has returned, it's too late to do anything with the response. At this point, entire response was already sent to the client and your code has no access to it.
以上声明在我看来并不正确.我不能在 filterChain.doFilter(request, response)
之后添加标题吗?如果不是为什么?
Above statement does not look right to me. Can't i add header after filterChain.doFilter(request, response)
? If not why ?
我正在使用 spring mvc.
i am using spring mvc.
推荐答案
在调用 filterChain.doFilter
之后,对响应做任何事情都为时已晚.此时,整个响应已经发送给客户端.
After filterChain.doFilter
is called it's too late to do anything with the response. At this point, the entire response was already sent to the client.
您需要将包装响应构建到您自己的类中,将这些包装器传递给 doFilter
方法并处理您的包装器中的任何处理.
You need to build a wrap response into your own classes, pass these wrappers into doFilter
method and handle any processing in your wrappers.
已经有一个可以扩展的响应包装器:HttpServletResponseWrapper
.例如:
There is already a response wrapper: HttpServletResponseWrapper
that you can extend. For example:
public class MyResponseRequestWrapper extends HttpServletResponseWrapper{
public MyResponseRequestWrapper(HttpServletResponse response) {
super(response);
}
}
您的过滤器:
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
HttpServletResponse myResponse = (HttpServletResponse) response;
MyResponseRequestWrapper responseWrapper = new MyResponseRequestWrapper(myResponse);
responseWrapper.addHeader("Access-Control-Allow-Origin", "*");
filterChain.doFilter(request, myResponse);
}
这篇关于在过滤器中添加响应头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!