How to Use Filter in Servlet 3 with @WebFilter Annotation

@WebFilter Annotation has been introduced in Java EE 6. It defines different element like filterName, asyncSupported and servletNames etc. @WebFilter cannot be used without web.xml because @WebFilter does not define order. @WebFilter reduces the other configuration in web.xml.


@WebFilter annotation declares a filter. The servlet container processes a filter at deployment time and associates to the specified URL, servlet and dispatcher. It does not defines order.

asyncSupported: It supports asynchronous operation in filter.
dispatcherTypes: It associates a dispatcher to a filter.
filterName: Defines a filter name.
initParams: Initialization parameter to the filter.
servletNames: Defines servlet to which the filter will be applied.
urlPatterns: Defines URL pattern.

@WebFilter Does Not Define the Order of Filter

@WebFilter has no element to define the order of filter of execution. We need to define order in web.xml. This may be because if we decide order of filter at class level using @WebFilter, then what if we include third party library which has filter with same order.

Example for @WebFilter with web.xml

Now find the example of @WebFilter. We are creating two filter and a servlet. The order of filter will be defined in web.xml. Find the filter one. Java By Kiran

Find the filter two.
Java By Kiran

Find the web.xml.
Java By Kiran

Java By Kiran

Java By Kiran

Find the servlet.
Java By Kiran

Java By Kiran

Java By Kiran


To run the demo deploy the war file and access URL
We will get output in console as below.

Java By Kiran