I want to make a Servlet filter that will read the contents of the Response after it\'s been processed and completed and return that information in XML or PDF or whatever.
Add this to the filter java file.
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();
}
}
Use the follow code:
HttpServletResponse httpResponse = (HttpServletResponse) response;
MyHttpServletResponseWrapper wrapper =
new MyHttpServletResponseWrapper(httpResponse);
chain.doFilter(request, wrapper);
String content = wrapper.toString();
The content variable now has the output stream. You can also do it for binary content.