4.6 Intercepting Filter
The Intercepting Filter pattern turns cross-cutting concerns (auth, logging, compression, encoding, rate-limiting…) into a chain of pluggable filters that a request passes through before reaching the real business handler, and that a response passes back through before returning. Business logic stays clean while common handling is managed centrally.
The lab below lets you advance a request step by step and watch it pass through the filter chain to the target and back — pre- and post-processing made plain.
A filter manager makes filters pluggable
class FilterManager {
private FilterChain chain = new FilterChain();
void addFilter(Filter f) { chain.addFilter(f); } // declarative add/remove
void filterRequest(Request r) { chain.execute(r); }
}
// Want a new cross-cutting concern? Write a Filter and register it; the target doesn't change a line
manager.addFilter(new AuthFilter());
manager.addFilter(new GzipFilter());Adding, removing, and reordering filters affects neither the business target nor the other filters. The lab below lets you toggle filters and watch the active filter chain change dynamically.
How it relates to Chain of Responsibility
Intercepting Filter and Chain of Responsibility (Section 3.1) are structurally very similar — both "pass a request through a line of handlers." The difference is emphasis:
- Chain of Responsibility: often "stop at the first capable handler"; the request is ultimately consumed by one handler.
- Intercepting Filter: usually "every filter participates," doing pre/post cross-cutting work; the request is ultimately handed to the target rather than swallowed by one filter.
Everywhere in reality
The Servlet Filter, the middleware pipelines of web frameworks (Express middleware, ASP.NET middleware, Spring interceptors/filters), and the plugin chains of API gateways — all are real incarnations of the intercepting filter. It solves the same class of problem as AOP (aspect-oriented programming): gather cross-cutting logic scattered everywhere into one composable layer.