This is a completely annoying problem that I had to handle several times, and I never found a satisfactory solution.
The main problem is that the servlet API will not help here, so you need to trick it. My solution is to write a subclass of HttpServletResponseWrapper that overrides the getWriter () and getOutput () methods and captures the data into the buffer. Then you forward () your request to the JSP URI you want to capture, substituting a wrapper response for the original response. Then you extract data from the buffer, process it and write the final result back to the original response.
Here is my code that does this:
public class CapturingResponseWrapper extends HttpServletResponseWrapper { private final OutputStream buffer; private PrintWriter writer; private ServletOutputStream outputStream; public CapturingResponseWrapper(HttpServletResponse response, OutputStream buffer) { super(response); this.buffer = buffer; } @Override public ServletOutputStream getOutputStream() { if (outputStream == null) { outputStream = new DelegatingServletOutputStream(buffer); } return outputStream; } @Override public PrintWriter getWriter() { if (writer == null) { writer = new PrintWriter(buffer); } return writer; } @Override public void flushBuffer() throws IOException { if (writer != null) { writer.flush(); } if (outputStream != null) { outputStream.flush(); } } }
The code to use it might be something like this:
HttpServletRequest originalRequest = ... HttpServletResponse originalResponse = ... ByteArrayOutputStream bufferStream = new ByteArrayOutputStream(); CapturingResponseWrapper responseWrapper = new CapturingResponseWrapper(originalResponse, bufferStream); originalRequest.getRequestDispatcher("/my.jsp").forward(originalRequest, responseWrapper); responseWrapper.flushBuffer(); byte[] buffer = bufferStream.toByteArray();
This is very ugly, but it is the best solution I have found. In case you are interested, the shell response should contain the original answer, because the servlet specification says that you cannot replace a completely different request or response object when forwarding, you should use the originals or their certified versions.
skaffman
source share