Introduction to filters in Servlets

Now, you all might be familiar to the generic word ‘Filter’. We use it in our day to day life. Filtering means that we streamline the bulk data specific to what we need and eliminating those that are very obvious to be out of the scope.

However, in Servlets,  Filters help in intercepting the various requests and responses to and from the server. Filters are nothing but the simple java classes, that are mapped with the web.xml to serve the purpose of a Filter.

In this demo, I will be writing a simple Filter and further try to explain how it actually works.

The javax.servlet.Filter interface has three methods namely doFilter(), init() and destroy().

We will first create a java class,, to serve as the Filter as:

Now next, map the Filter in web.xml as:

You can see that the <url-pattern> has ‘/*’  in it, which means that the filter will be applied to all the servlets existing in a web application. Also note that there can be as many number of filters in an application and they get executed in the same order as they are present in the web.xml. Here, chain.doFilter method plays it’s role such that the parameters aren’t lost while traversing through different filters.

Please do write in your queries as comment to this post.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.