This is an ideal use case for Apache Commons IO CountingOutputStream . You need to create a Filter that uses an HttpServletResponseWrapper to replace the OutputStream with that answer and replace Writer and also wrap the wrapped OutputStream . Then take an instance of HttpServletResponseWrapper in the request area to get getByteCount() from CountingOutputStream .
Here is an example of running CountingFilter :
public class CountingFilter implements Filter { @Override public void init(FilterConfig arg0) throws ServletException {
CountingServletResponse :
public class CountingServletResponse extends HttpServletResponseWrapper { private final long startTime; private final CountingServletOutputStream output; private final PrintWriter writer; public CountingServletResponse(HttpServletResponse response) throws IOException { super(response); startTime = System.nanoTime(); output = new CountingServletOutputStream(response.getOutputStream()); writer = new PrintWriter(output, true); } @Override public ServletOutputStream getOutputStream() throws IOException { return output; } @Override public PrintWriter getWriter() throws IOException { return writer; } @Override public void flushBuffer() throws IOException { writer.flush(); } public long getElapsedTime() { return System.nanoTime() - startTime; } public long getByteCount() throws IOException { flushBuffer();
CountingServletOutputStream :
public class CountingServletOutputStream extends ServletOutputStream { private final CountingOutputStream output; public CountingServletOutputStream(ServletOutputStream output) { this.output = new CountingOutputStream(output); } @Override public void write(int b) throws IOException { output.write(b); } @Override public void flush() throws IOException { output.flush(); } public long getByteCount() { return output.getByteCount(); } }
You can use it on any page (not even JSF) as follows:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <title>Counting demo</title> </h:head> <h:body> <h1>Hello World</h1> </h:body> </html>
BalusC Jul 11 '10 at 1:36
source share