使用HttpServletResponseWrapper截获返回数据流

在Java Web开发中,我们经常需要拦截http请求,去做一些转发或者是校验等事情。这类工作通常filter可以很轻松的搞定,但这一般都是拦截请求。而我们有时候也会有一些需求,比如说是拦截服务器的返回(Response),希望在数据流在服务器端处理完毕,且返回浏览器之前,在这中间做一些自己的事情。网上搜了搜,发现资源很少。于是自己实现了一版,跟大家分享一下。主要用到了HttpServletResponseWrapper获取到数据流,然后通过response.getWriter().write来回写数据。

使用HttpServletResponseWrapper截获返回数据流

HttpStreamFilter.java
package test; import java.io.BufferedReader; import java.io.FileReader; import java.io.File; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.concurrent.ConcurrentHashMap; public class HttpStreamFilter implements Filter { public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)arg0; HttpServletResponse response = (HttpServletResponse)arg1; WrapperResponse wrapperResponse = new WrapperResponse(response); chain.doFilter(request, wrapperResponse); String html = wrapperResponse.getContent(); response.setContentLength(-1); response.getWriter().write( filterHTML(html) ); } public void init(FilterConfig filterConfig) throws ServletException { } public void destroy() {} public String filterHTML(String html) throws IOException { return html.replace("script", ""); } }
WrapperResponse.java
package test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; public class WrapperResponse extends HttpServletResponseWrapper { private class ResponsePrintWriter extends PrintWriter { ByteArrayOutputStream output; public ResponsePrintWriter(ByteArrayOutputStream output) { super(output); this.output = output; } public ByteArrayOutputStream getByteArrayOutputStream() { return output; } } private ResponsePrintWriter writer; private ByteArrayOutputStream output; public WrapperResponse(HttpServletResponse httpServletResponse) { super(httpServletResponse); output = new ByteArrayOutputStream(); writer = new ResponsePrintWriter(output); } public void finalize() throws Throwable { super.finalize(); output.close(); writer.close(); } public String getContent() { try { writer.flush(); return writer.getByteArrayOutputStream().toString("GBK"); } catch(UnsupportedEncodingException e) { return "UnsupportedEncoding"; } } public void close() throws IOException { writer.close(); } public PrintWriter getWriter() throws IOException { return writer; } }

相关阅读