这是一个有点疯狂的想法,但我可能会这样解决。
如果您真的无法触摸损坏的过滤器(真的吗?),请在损坏的过滤器之前编写另一个过滤器。
这看起来比实际复杂,但这只是因为 Java 的冗长,所以请多多包涵。
基本上它所做的是它用于在过滤器HttpServletResponseWrapper
中包装/“覆盖”response.getWriter()
以及在链中跟随它的 servlet。
因此,当您损坏的 Filter 调用response.getWriter()
时,它将改为获得一个代理 PrintWriter ,该代理仅response.getWriter()
在第一次实际写入时才调用 real 。
response.getWriter()
那么如果损坏的过滤器调用而不写入它就不再重要了。
我还没有实际测试过这段代码,但我相信它应该可以工作。
请注意,这假定损坏的过滤器调用response.getWriter()
而没有实际编写一些东西。如果损坏的过滤器写了一些东西,然后您也尝试向其写入 PDF,则输出无论如何都会损坏。
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
public class BrokenWriterGetterFixingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, final ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
filterChain.doFilter(servletRequest, new BrokenWriterGetterFixingResponseWrapper((HttpServletResponse) servletResponse));
}
@Override
public void destroy() {
}
private static class BrokenWriterGetterFixingResponseWrapper extends HttpServletResponseWrapper {
public BrokenWriterGetterFixingResponseWrapper(HttpServletResponse response) {
super(response);
}
@Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(new BrokenWriterGetterFixingWriter(getResponse()));
}
}
private static class BrokenWriterGetterFixingWriter extends Writer {
private PrintWriter responseWriter;
private final ServletResponse response;
public BrokenWriterGetterFixingWriter(ServletResponse response) {
this.response = response;
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
getResponseWriter().write(cbuf, off, len);
}
@Override
public void flush() throws IOException {
getResponseWriter().flush();
}
@Override
public void close() throws IOException {
getResponseWriter().close();
}
private PrintWriter getResponseWriter() throws IOException {
if (null == responseWriter) {
responseWriter = response.getWriter();
}
return responseWriter;
}
}
}