我希望在doFilter()
函数完成运行后添加一个 HTTP 标头。
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResp = (HttpServletResponse) response;
try {
chain.doFilter(request, httpResp);
} finally {
httpResp.setHeader("ADD A HEADER: ", "HEADER");
}
}
似乎doFilter
刷新了响应。
更新:
谢谢。查看 IgorMadjeric 和richardtz 的答案后,我决定尝试响应包装器:
这是包装器:
public class BufferedHttpServletResponse extends HttpServletResponseWrapper {
public BufferedHttpServletResponse(HttpServletResponse response) {
super(response);
}
public void flushBuffer() {
System.out.println("flush");
}
}
这是修改后的代码:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResp = (HttpServletResponse) response;
try {
BufferedHttpServletResponse bufferedResponse = new BufferedHttpServletResponse(httpResp);
chain.doFilter(request, bufferedResponse);
} finally {
bufferedResponse.setHeader("ADD A HEADER: ", "HEADER");
}
}
仍然无法正常工作。我做错什么了吗?