Java Servlet 过滤器 - 根据状态修改响应头 [英] Java Servlet Filter - Modify response headers based on status
问题描述
我正在尝试编写一个 servlet 过滤器,它将根据请求的状态向响应添加标头.我知道在传递给 chain.doFilter
之前我必须用 HttpServletResponseWrapper 包装响应,但标头永远不会被发送,所以我显然错过了一些非常明显的东西.
I'm trying to write a servlet filter that will add headers to the response depending on the status of the request. I know I have to wrap the response with a HttpServletResponseWrapper before passing to the chain.doFilter
but the headers never get sent, so I'm obviously missing something very obvious.
代码看起来像:
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(httpServletResponse);
chain.doFilter(request, responseWrapper);
if(responseWrapper.getStatus() < 400)
{
responseWrapper.addHeader("X-Custom-Foobar", "abc");
}
}
是否需要在包装器中捕获某些内容以防止响应在检查完成之前发送到客户端?
Is there something I have to capture in the wrapper to prevent the response from going out to the client until the check is complete?
推荐答案
所以这个规范令人沮丧的部分是你必须完全拦截 ServletOutputStream
并缓冲它.我结束了这里的例子:: https://stackoverflow.com/a/11027170/76343
So the frustrating part about this spec is that you have to completely intercept the ServletOutputStream
and buffer it. I ended up following the example here :: https://stackoverflow.com/a/11027170/76343
基类 HttpServletResponseWrapper
是一个完整的传递,一旦关闭输出流,对响应的所有进一步修改都会静音.
The base class HttpServletResponseWrapper
is a complete passthrough and as soon as the output stream is closed, all further modifications to the response are mute.
不幸的是,似乎没有更优雅的方式来实现这一点.
Unfortunately there doesn't seem to be a more elegant way to accomplish this.
这篇关于Java Servlet 过滤器 - 根据状态修改响应头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!