javaservletsservlet-filtersjetty-8

Servlet Response Wrapper ignored for static content


I've created server filter, that counts response size. It does that by creating response wrapper, which wraps ServletOutputStream with Apache Commons CountingOutputStream. Also, wrapper creates PrintWriter with wrapped stream. So in theory, whatever method would be used to create actual output, it should go through CountingOutputStream.

The problem is that, while whole thing works for typical servlet requests, it fails for static content. To be precise, the request is being picked up by filter, response wrapper is created and chain.doFilter() called. However when it returns, the wrapped stream claims no data was sent, while in reality data was sent. After further debugging it appears that during serving static content neither getOutputStream() nor getWriter() are called on the response wrapper.

The filter and app are running on Jetty 8.1.x. I've skimmed through Jetty's default servlet and it appears static content is being served in the usual way (that is by obtaining output stream and writting to it).

So the question is: Why the wrapper methods are being ignored?


Solution

  • The problem turned out to be me expecting something not really possible. I was making a request to non-existent static resource. I still expected some data to go through filter, because http client was getting bunch of headers and my filter was reporting 0 bytes which simply felt wrong. However, it turned out that filters only do see raw data produced by servlet (or in case of static content and jetty - handler). They can't see headers as they are added later by the server, when all of the app code was already executed. While I'd like to have total response size (headers and content) it appears I have to settle down with only content beng measured.