Think of filters as being “stackable”

The servlet spec doesn’t dictate how the chain.doFilter(req, resp) method is handled inside the container. In practice, though, you can think of the process of filters chaining to each other as if they were simply method calls on a single stack. We know there’s more going on behind the scenes in the Container, but we don’t care, as long as we can predict how our filters will run, and a conceptual (if not physical) stack lets us do that.

A conceptual call stack example

In this example, a request for ServletA will be filtered by two filters, Filter3, then Filter7.

This “conceptual stack” is just a way to think about filter chain invocations. We don’t know (or care) how the Container actually implements this—but thinking of it this way lets you predict how your filter chain will behave.

image with no caption

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.