2

我正在尝试将某个字符串附加到发送回客户端的每个响应中。为此,我使用如下所示的过滤器:

public class OutFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain filterChain) throws IOException, ServletException {
        PrintWriter out = resp.getWriter();
        CharResponseWrapper wrapper = new CharResponseWrapper(
        (HttpServletResponse) resp);

        filterChain.doFilter(request, wrapper);

        out.print(wrapper.toString());
        out.print("ADDITIONAL CONTENT".toString());
    }
}

我知道在 doFilter() 方法通过后我无法更改 ServletResponse 对象,所以这就是我使用包装器进行 HTTP-Response 的原因:

public class CharResponseWrapper extends HttpServletResponseWrapper {

    private CharArrayWriter output;
    private ServletOutputStream stream;

    public String toString() {
        return output.toString();
    }

    public CharResponseWrapper(HttpServletResponse response) throws IOException {
        super(response);
        output = new CharArrayWriter();
        stream = new ServletOutputStream() {

            @Override
            public void write(int b) throws IOException {
                // TODO Auto-generated method stub

            }
        };
    }

    public PrintWriter getWriter() {
        return new PrintWriter(output);
    }

    public ServletOutputStream getOutputStream() {
        return stream;
    }

}

我的 web.xml 看起来像这样:

<filter>
    <filter-name>OutFilter</filter-name>
    <filter-class>com.foo.OutFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>OutFilter</filter-name>
    <url-pattern>/1.html</url-pattern>
    <url-pattern>/2.html</url-pattern>
    <url-pattern>/3.html</url-pattern>
    <url-pattern>/statistics</url-pattern>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

统计 servlet 如下所示:

public class Statistics extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        resp.getWriter().print("<b>Hello, World</b>");

    }
}

关键是在所有访问文件的 HTTP 响应末尾附加“附加内容”,因此 1.html、2.html、3.html 以及 /statistics(服务于 Statistics Servlet)。

访问 servlet 工作正常 - 我得到了 html 内容,然后是“附加内容”字符串。但是,访问任何一个静态 html 文件都会产生以下错误:

java.lang.IllegalStateException: NO CONTENT

我究竟做错了什么?

感谢所有帮助。

4

0 回答 0