The outputStream used to generate the final packet is not the one in the the wrapper but the one in the original ServletResponse
object (kept in super class ServletResponseWrapper
). We just need to write to both stream.
This behavior looks very strange to me since dofilter
return the wrapper's reference. You are welcome if you have any explanation.
The workaround:
class ReadableContentHttpServletResponse extends HttpServletResponseWrapper {
private ByteArrayOutputStream outputStream;
private ServletOutputStream servletOutputStream;
public ReadableContentHttpServletResponse(HttpServletResponse response) throws IOException {
super(response);
outputStream = new ByteArrayOutputStream();
final ServletOutputStream responseOutputStream = response.getOutputStream();
servletOutputStream = new ServletOutputStream() {
private WriteListener writeListener = null;
@Override
public void write(int b) throws IOException {
outputStream.write(b);
responseOutputStream.write(b);
if (writeListener != null) {
writeListener.notify();
}
}
...