Filter servlet example

Filter servlet example explained here in only 2 minutes.Filter object is generally used for filtering both request or responce made to your web application.

Where we use filter in servlet?

Case 1:

In day to day life when we make calls the call is intercepted and checked whether you are having sufficient balance.

If balance==0 then

     Filter says “You don’t have enough balance and call terminates.”


     your call is connected.


When you check website and you are not logged in filter intercepts you request and takes you to login screen.

Folder structure

This is how your folder structure should be.

How to Implement Filter

Filter is an interface in package javax.servlet. For details please read

Steps for implementing filter

Create the class to implement filter interface.Declare that class to bind the filter to perticular url in web.xml.Now access the resource using url.

Create the class to implement filter interface.

create package com.filter

Right click package com.filter pop up will appear

Select new->Filter->

Now see the steps in the screen shots.

Create Filter class.

Declare the url pattern it means the logical url how you will access the filter class.

click finish.

Congrats ! Your filter is created under package com.filter.

Just write 

I would recommend you to read Head first Jsp and Servlet

inside doFilter().


Now bind the filter with the perticular url.

What this code does is binds the filter to the url defined inside url pattern 


so whatever may be after / filter will always execute.

To define filter we should specify name using 

.To specify the location where filter implementation lies (class GreetingFilter) we should define using 

.Till this point you are just specifying the filter properties you did not bind it to any url.

Binding is done by using this tag we define logical name of file 

.now we define the url pattern which should be intercepted by filter using 


suppose you wanted to execute this filter on url http://localhost:7081/JEEDemo/index then your will be as follow.


The target where it executes


Final Step Execute Url where filter executes

Run project on server.

exeute this url http://localhost:7081/JEEDemo/index

Congrats you have created and launched your first filter servlet. We wish you good luck for your learning.If you really loved this article please fell free to share and comment.

Download Full Example

Click here

Leave a Reply

Your email address will not be published. Required fields are marked *