Is there a way I can capture the output of a servlet, without immediately sending it to the client response stream?

Alex Chaffee

[In other words, I want to override/specify the response.getServletOutputStream(). To be even more specific, why is there not something like response.setServletOutputStream()?]

The original design of servlets was rather simplistic; it conceived of a single request and a single response stream. As it evolved, it has added bits and pieces (like the RequestDispatcher) to allow more servlet-to-servlet communication, including, and forwarding, but it is still mostly inadequate to do things like filtering or capturing the output of another Servlet.

Rumor has it that the next version of the Servlet specification will have explicit support for this, but until then, there are a number of solutions.

The simplest solution is to use the URL class to initiate an HTTP connection from your servlet. Specify the URL of the target servlet, and capture the result from the URL's InputStream. See How can I include content from a URL, not from a local file? and How can I download files from a URL using HTTP?.

Jason Hunter's CacheHttpServlet contains a class called CacheHttpResponse (and a corresponding CacheServletOutputStream) that saves all its output to a buffer. In theory, you can create one of these, and pass it into a RequestDispatcher's forward() or include() methods, then read the buffer when it's complete. You may have to massage some fields so they match the caller's ServletResponse. If anybody tries this, please let me know (submit a feedback)!

Also, Resin has a feature called Servlet Filtering that may do what you want.

See also