Tuesday, 13 May 2008

Custom Servlet Filter Chains Injection

Lately I had the task to add additional Java Servlet Filters at runtime to an existing Filter stack. Logically that sounds pretty simple but the implementation was not that simple and I had to use some Swiss ingenuity to make it work. A Filter has one important message called doFilter( Request, Response, Chain ). In order to make sure that the chain of filters is executed the Filter has in some place to call the method doFilter( Request, Response ) and the Filter Chain instance will then call the next filter in the chain or the target resource if there are no more filters. Because a filter has an in piece (the code before the chain.doFilter() call) and an out piece making it impossible to just loop through my own filters and then call the next through the filter chain. In addition the Filter Chain does not have any add/remove method to inject filters at runtime. Well, now what to do?

After a few minutes it finally dawned on my that I could replace the Filter Chain with my own one to make sure that my filters are included. But then what do I do with the remaining filters in the original filter chain. Well, I just do the same to it as the original filter chain does when it reached it end, I just call the target which in this case is the original filter chain. This led me to the ProxyFilterChain class that looks like that:

  keep on reading here
                                                                    

Posted by schaefera at 5:51 PM in Java