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.
Spring now has feature for it . All you need to do is use [ContentCachingResponseWrapper], which has method public byte[] getContentAsByteArray() .
I Suggest to make WrapperFactory which will allow to make it configurable, whether to use default ResponseWrapper or ContentCachingResponseWrapper.
I don't much know that you can get data out of an HttpServletResponse object as such. It may make more sense to structure your application such that requests are proxied to the appropriate handlers and passed about with data transfer objects, from which you can build the appropriate final response. In this manner, you never modifiy more than one response object or need to read from such.
Not a direct answer, I know, but that's how I'd do it give the question.
I don't believe you can necessarily do this given that writing to the output stream may result in the data being flushed to the client prior to any servlet filters being invoked post-population. As iftrue suggests, a different architecture would be advisable, to generate your XML (say) and then regenerate in whatever output format you desire.
EDIT: Having read your response to iftrue's posting, if you really can't interfere with the current processing, perhaps you require a servlet to proxy your request, capture the output from the original output, and then munge as appropriate. Very nasty, however :-(
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With