Close

Create Servlet Filter using @WebFilter

[Last Updated: Nov 4, 2018]

@WebFilter annotation is used to define a Servlet Filter component in a web application.

A filter dynamically intercepts requests and responses. It transform or use the information contained in the requests or responses. Filters typically do not themselves create responses, but instead provide general functionality that can be attached to any type of servlet or JSP page.

In this example we are going to demonstrate how to profile internal servlets performance. We are going to create our profile filter using @WebFilter annotation. Let's consider following web.xml filter configuration first.

<filter>
    <filter-name>profiler</filter-name>
    <filter-class>com.logicbig.filter.Profiler</filter-class>
    <init-param>
        <param-name>env</param-name>
        <param-value>dev</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>profiler</filter-name>
    <url-pattern>/search/*</url-pattern>
</filter-mapping>

We are going to create equivalent annotation based filter.

  1. Prepare project
    • Create web application using maven-archetype-webapp, steps here.
    • Delete web.xml, we don't need it at all.
    • Delete webapp/index.jsp.
    • In pom.xml add dependency of javax.servlet-api:3.0.1
    • In pom.xml also add tomcat7-maven-plugin to run it as embedded server.
  2. Create a filter class Profiler, annotated with @WebFilter. Also we are going to add all configurations mentioned in above web.xml.
  3. Create a servlet class SearchController using annotation @WebServlet with the same url pattern so that we can test our profiler filter.
  4. Now we are going to run our web application from root folder:
    mvn clean tomcat7:run-war
  5. Put following url in your browser:
    http://localhost:8080/webfilter-example/search
    You should see the page output as printed in the servlet. Also see the console output where we ran the tomcat server. At the end you will see:
      Time taken for request to complete:  103ms
      Request url : http://localhost:8080/webfilter-example/search 


Example Project

Dependencies and Technologies Used:

  • Java Servlet API 3.0.1
  • JDK 1.8
  • Maven 3.0.4

Webfilter Example Select All Download
  • web-filter-example
    • src
      • main
        • java
          • com.logicbig.filter
            • Profiler.java
            • com.logicbig.servlet

    See Also