Video in progress

Strong Junior 🧭 Design patterns

Explain the Chain of Responsibility pattern using the servlet Filter.

A request passes through a series of handlers one after another; each does its own job and then passes it on, or stops the chain itself. Servlet Filters work exactly like this: each filter either calls chain.doFilter() or doesn't.

📖 Answer

public class ApiKeyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        var http = (HttpServletRequest) req;
        if (http.getHeader("X-Api-Key") == null) {
            ((HttpServletResponse) res).sendError(401);
            return;                 // the chain is cut here
        }
        chain.doFilter(req, res);   // the next filter or the servlet
        // the code here runs after the response comes back
    }
}

The important points:

  • each filter knows only one job: logging, CORS, authentication, gzip;
  • filters don't know each other: the order is set in configuration;
  • the code before and after chain.doFilter corresponds to the "entry" and "exit" stages.

A practical mistake: forgetting to call chain.doFilter. Then the request never reaches the controller, the client gets an empty 200 response, and you see no error in the log. In Spring Boot you control the filter order with @Order or FilterRegistrationBean.setOrder.

Other examples: Spring Security filters, Spring MVC's HandlerInterceptor, the Netty pipeline.