我想制作一个Servlet过滤器,它将在处理完成后读取Response的内容,并以XML或PDF或其他方式返回该信息.但我不知道如何从HttpServletResponse对象中获取任何信息.我怎样才能获得这些信息?
将其添加到过滤器java文件中.
static class MyHttpServletResponseWrapper extends HttpServletResponseWrapper { private StringWriter sw = new StringWriter(BUFFER_SIZE); public MyHttpServletResponseWrapper(HttpServletResponse response) { super(response); } public PrintWriter getWriter() throws IOException { return new PrintWriter(sw); } public ServletOutputStream getOutputStream() throws IOException { throw new UnsupportedOperationException(); } public String toString() { return sw.toString(); } }
使用以下代码:
HttpServletResponse httpResponse = (HttpServletResponse) response; MyHttpServletResponseWrapper wrapper = new MyHttpServletResponseWrapper(httpResponse); chain.doFilter(request, wrapper); String content = wrapper.toString();
内容变量现在具有输出流.您也可以为二进制内容执行此操作.