利用HttpServletResponseWrapper修改Response对象

使用servlet从HttpServletResponse读取输出流,并对输出流做一些修改,但是如果我们直接对原始response进行操作则会造成输出流提前打开或者关闭,导致不能从一次请求中完成对输出流的修改。

所以我们可以通过继承HttpServletResponseWrapper对象来获取原始的输出流,通过PrintWriter将输出流写入到Buffer中。

public class ResponseWrapper extends HttpServletResponseWrapper {
    private PrintWriter cachedWriter;
    private CharArrayWriter bufferedWriter;

    /**
     * Constructs a response adaptor wrapping the given response.
     *
     * @param response The response to be wrapped
     * @throws IllegalArgumentException if the response is null
     */
    public ResponseWrapper(HttpServletResponse response) {
        super(response);
        bufferedWriter = new CharArrayWriter();
        cachedWriter = new PrintWriter(bufferedWriter);
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        return cachedWriter;
    }

    /**
     * 获取原始HTML
     *
     * @return
     */
    public String getResult() {
        byte[] bytes = bufferedWriter.toString().getBytes();
        try {
            return new String(bytes, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }
}

通过过滤器拦截Response对象,然后就可以对输出流进行操作了。

public class ResponseFilter implements Filter {
    @Override
    public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ResponseWrapper wrapper = new ResponseWrapper((HttpServletResponse) response);
        chain.doFilter(request, wrapper);
        String result = wrapper.getResult();
        response.getOutputStream().write(result.getBytes());
    }

    @Override
    public void destroy() {

    }
}

 

posted @ 2017-02-09 19:33  rk0x1  阅读(3663)  评论(1编辑  收藏  举报