Java - 从过滤器更改Servlet响应

时间:2013-05-02 10:27:41

标签: java filter response

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

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响应使用Wrapper的原因:

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(其中)提供统计服务)。

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

java.lang.IllegalStateException: NO CONTENT

我做错了什么?

感谢您的帮助。

0 个答案:

没有答案