Three ways filters are like servlets
Kim’s right, filters live in the Container. In many ways they’re similar to their co-residents, servlets. Here are a few ways in which filters are like servlets:
The Container knows their API
Filters have their own API. When a Java class implements the Filter interface, it’s striking a deal with the Container, and it goes from being a plain old class to being an official J2EE Filter. Other members of the filter API allow filters to get access to the ServletContext, and to be linked to other filters.
The Container manages their lifecycle
Just like servlets, filters have a lifecycle. Like servlets, they have init() and destroy() methods. Similar to a servlet’s doGet()/doPost() method, filters have a doFilter() method.
They’re declared in the DD
A web app can have lots of filters, and a given request can cause more than one filter to execute. The DD is the place where you declare which filters will run in response to which requests, and in which order.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access