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.

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.