I would really like to be able to intercept and decorate a HttpServletRequest with a ServletFilter transparently to the underlying Servlet. My basic goal is to count the number of bytes transmitted and time to process the request and do something with that information. In order to do this I was hoping to enlist a ServletFilter via a web-fragment by simply including a jar in the libs for the application. This works fine, except that the FilterChain returns prior to processing the request when the underlying Servlet goes async (as expected). Is there some standard way to handle this sort of thing? I know there are async listeners that can be registered after the creation of the async context, but I would rather that the Servlet and Servlet Filter had no knowledge of each other.
Define a ServletRequestWrapper that overrides startAsync, calls super.startAsync(), and then registers your AsyncListener on the resulting AsyncContext.
In your filter, wrap the request in that wrapper and call the next filter with that instead of the original request.
It's not trivial, took me a bit to figure it out. There is wording in the Servlet Spec 3 that suggests you can add AsyncListeners to a ServletContext, which would make it all a bit easier (although possibly unimplementable underneath). Maybe that was the original intention and they had to change it.
Indeed. The Servlet 3.0 documentation feels a little lacking to me. I have been surprised at the dearth of good information available when searching on Google; normally there is too much to sort through without extreme specificity, but for Servlet 3.0 it seems to be the opposite. Luckily there are still some community resources available.