36

我一直在网络和 stackoverflow 中搜索某人使用 servlet 过滤器将内容插入响应的示例,但只能找到人们捕获/压缩输出和/或更改标头的示例。我的目标是在所有 HTML 响应的结束 </body> 之前附加一大块 HTML。

我正在研究一种扩展 HttpServletResponseWrapper 以使用我自己的 PrintWriter 的解决方案,然后覆盖其上的写入方法。在 write 方法中,我存储最后 7 个字符以查看它是否等于结束正文标记,然后我编写我的 HTML 块加上结束正文标记,然后继续对文档的其余部分进行正常写入操作。

我觉得一定有人已经解决了这个问题,而且可能比我更优雅。我将不胜感激任何有关如何使用 servlet 过滤器将内容插入响应的示例。

更新

回应评论,我也试图从http://www.oracle.com/technetwork/java/filters-137243.html实现 CharResponseWrapper 。这是我的代码:

PrintWriter out = response.getWriter();
CharResponseWrapper wrappedResponse = new CharResponseWrapper(
        (HttpServletResponse)response);

chain.doFilter(wrappedRequest, wrappedResponse);
String s = wrappedResponse.toString();

if (wrappedResponse.getContentType().equals("text/html") &&
        StringUtils.isNotBlank(s)) {
    CharArrayWriter caw = new CharArrayWriter();
    caw.write(s.substring(0, s.indexOf("</body>") - 1));
    caw.write("WTF</body></html>");
    response.setContentLength(caw.toString().length());
    out.write(caw.toString());
}
else {
    out.write(wrappedResponse.toString());
}

out.close();

我也在包装请求,但该代码有效并且不应该影响响应。

4

4 回答 4

45

我正在使用的代码库在处理响应时调用 getOutputStream 方法,而不是 getWriter ,因此其他答案中包含的示例无济于事。这是一个更完整的答案,它适用于 OutputStream 和 PrintWriter,如果写入器被访问两次,甚至会正确出错。这源自一个很好的例子,DUMP REQUEST AND RESPONSE USING JAVAX.SERVLET.FILTER

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class MyFilter implements Filter
{
    private FilterConfig filterConfig = null;

    private static class ByteArrayServletStream extends ServletOutputStream
    {
        ByteArrayOutputStream baos;

        ByteArrayServletStream(ByteArrayOutputStream baos)
        {
            this.baos = baos;
        }

        public void write(int param) throws IOException
        {
            baos.write(param);
        }
    }

    private static class ByteArrayPrintWriter
    {

        private ByteArrayOutputStream baos = new ByteArrayOutputStream();

        private PrintWriter pw = new PrintWriter(baos);

        private ServletOutputStream sos = new ByteArrayServletStream(baos);

        public PrintWriter getWriter()
        {
            return pw;
        }

        public ServletOutputStream getStream()
        {
            return sos;
        }

        byte[] toByteArray()
        {
            return baos.toByteArray();
        }
    }

    public class CharResponseWrapper extends HttpServletResponseWrapper
    {
        private ByteArrayPrintWriter output;
        private boolean usingWriter;

        public CharResponseWrapper(HttpServletResponse response)
        {
            super(response);
            usingWriter = false;
            output = new ByteArrayPrintWriter();
        }

        public byte[] getByteArray()
        {
            return output.toByteArray();
        }

        @Override
        public ServletOutputStream getOutputStream() throws IOException
        {
            // will error out, if in use
            if (usingWriter) {
                super.getOutputStream();
            }
            usingWriter = true;
            return output.getStream();
        }

        @Override
        public PrintWriter getWriter() throws IOException
        {
            // will error out, if in use
            if (usingWriter) {
                super.getWriter();
            }
            usingWriter = true;
            return output.getWriter();
        }

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

    public void init(FilterConfig filterConfig) throws ServletException
    {
        this.filterConfig = filterConfig;
    }

    public void destroy()
    {
        filterConfig = null;
    }

    public void doFilter(
            ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException
    {
        CharResponseWrapper wrappedResponse = new CharResponseWrapper(
                (HttpServletResponse)response);

        chain.doFilter(request, wrappedResponse);
        byte[] bytes = wrappedResponse.getByteArray();

        if (wrappedResponse.getContentType().contains("text/html")) {
            String out = new String(bytes);
            // DO YOUR REPLACEMENTS HERE
            out = out.replace("</head>", "WTF</head>");
            response.getOutputStream().write(out.getBytes());
        }
        else {
            response.getOutputStream().write(bytes);
        }
    }
}
于 2013-02-06T23:57:45.060 回答
18

您将需要实现 HttpServletResponseWrapper 来修改响应。请参阅此文档The Essentials of Filters,它有一个转换响应的示例,这比您想要的要多

编辑

我尝试了一个带有响应过滤器的简单 Servlet,它运行良好。Servlet 输出字符串Test,响应过滤器将字符串附加到它上面filtered,最后当我从浏览器运行时,我得到了Test filtered你想要实现的响应。

我确实在 Apache Tomcat 7 上运行了以下代码,它毫无例外地工作。

小服务程序:

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

   response.getWriter().println("Test");

}

筛选:

public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

    System.out.println("BEFORE filter");
    PrintWriter out = response.getWriter();
    CharResponseWrapper responseWrapper = new CharResponseWrapper(
            (HttpServletResponse) response);

    chain.doFilter(request, responseWrapper);

    String servletResponse = new String(responseWrapper.toString());

    out.write(servletResponse + " filtered"); // Here you can change the response


    System.out.println("AFTER filter, original response: "
            + servletResponse);

}

CharResponseWrapper(和文章一样)

public class CharResponseWrapper extends HttpServletResponseWrapper {
    private CharArrayWriter output;

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

    public CharResponseWrapper(HttpServletResponse response) {
        super(response);
        output = new CharArrayWriter();
    }

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

web.xml

<servlet>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>TestServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>TestServlet</servlet-name>
    <url-pattern>/TestServlet</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>TestFilter</filter-name>
    <filter-class>MyFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>TestFilter</filter-name>
    <url-pattern>/TestServlet/*</url-pattern>
</filter-mapping>
于 2013-02-06T19:08:27.733 回答
4

iTech 的答案部分对我有用,这是基于该响应..

但是您必须注意,似乎某些 Web 服务器(和 AppEngine 标准)在第一次调用过滤器内的 chain.doFilter 后关闭了 outputStream..

因此,当您需要在预先保存的 PrintWritter 上进行写入时,流将关闭并且您会看到一个空白屏幕。(我什至没有收到错误来意识到发生了什么)。

所以我的解决方案是创建一个“虚拟”ServletOutputStream 并返回到我的 ResponseWrapper 的 getOutputStream 方法中。

这些更改加上 iTech 的解决方案使我能够在 json 响应中的 html 中插入完全呈现的 jsp 响应(正确转义引号等冲突字符)。

这是我的代码:

我的过滤器

@WebFilter({"/json/*"})    
public class Myfilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //Save original writer
        PrintWriter out = response.getWriter(); 
        //Generate a response wrapper with a different output stream
        ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response);
        //Process all in the chain (=get the jsp response..)
        chain.doFilter(request, responseWrapper);
        //Parse the response
        out.write("BEFORE"+responseWrapper.toString()+"AFTER"); //Just + for clear display, better use a StringUtils.concat
    }
    @Override
    public void destroy() {}
}

我的ResponseWrapper

public class ResponseWrapper extends HttpServletResponseWrapper {
    private StringWriter output;
    public String toString() {
        return output.toString();
    }
    public ResponseWrapper(HttpServletResponse response) {
        super(response);
        //This creates a new writer to prevent the old one to be closed
        output = new StringWriter();
    }
    public PrintWriter getWriter() {
        return new PrintWriter(output,false);
    }
    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        //This is the magic to prevent closing stream, create a "virtual" stream that does nothing..
        return new ServletOutputStream() {
            @Override
            public void write(int b) throws IOException {}
            @Override
            public void setWriteListener(WriteListener writeListener) {}
            @Override
            public boolean isReady() {
                return true;
            }
        };
    }
}
于 2018-03-13T15:37:08.340 回答
1

伟大的!但请更新内容长度,

        String out = new String(bytes);
        // DO YOUR REPLACEMENTS HERE
        out = out.replace("</head>", "WTF</head>");
        response.setContentLength(out.length());
        response.getOutputStream().write(out.getBytes());
于 2019-07-04T17:14:22.750 回答