@WebFilter Annotation Example

The @WebFilter annotation is used to define a Filter in a web application. This annotation is specified on a class and contains metadata about the filter being declared.
This annotation is processed by the container at deployment time, and the corresponding filter applied to the specified URL patterns, servlets, and dispatcher types.
The classes annotated with @WebFilter must implement javax.servlet.Filter.

@WebFilter Annotation Attributes

Below diagram shows a class diagram of @WebServlet annotation:
Let me list out all the attributes used to configure Filter using @WebFilter annotation:
  1. String filterName - Name of the filter
  2. String[] urlPatterns - Provides an array of values or urlPatterns to which the filter applies
  3. DispatcherType[] dispatcherTypes - Specifies the types of dispatcher (Request/Response) to which the filter applies
  4. String[] servletNames - Provides an array of servlet names
  5. String displayName - Name of the filter
  6. String description - Description of the filter
  7. WebInitParam[] initParams - The array of initialization parameters for this filter
  8. Boolean asyncSupported - Asynchronous operation supported by this filter
  9. String smallIcon - Defines a small icon for this filter, if present
  10. String largeIcon - Defines a large icon for this filter, if present
The default name of the Filter if not specified is the fully qualified class name. The urlPatterns attribute, servletNames attribute or the value attribute of the annotation must be specified. All other attributes are optional with default settings.

@WebFilter Annotation Example

Let's develop a complete example to demonstrate the usage of @WebFilter annotation. The classes annotated with @WebFilter must implement javax.servlet.Filter.

Step 1: Add servlet dependency to pom.xml

Let's first add servlet 4.0.1 dependency to our pom.xml:
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>net.javaguides.servlet.tutorial</groupId>
    <artifactId>java-servlet-tutorial</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>java-servlet-tutorial Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>java-servlet-tutorial</finalName>
    </build>
</project>

Step 2: Create Filter using @WebFilter Annotation

The following example describes how to use @WebFilter annotation. It is a simple AuthFilter that displays the value of username and password and the current time timestamp on the console. That means the filter works like an interface layer between the request and the response. Here we use "/*" for urlPattern. It means this filter is applicable for all the servlets.
package net.javaguides.servlet.tutorial.httpservlet;

import java.io.IOException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.*;
import java.util.*;

// Implements Filter class

@WebFilter(urlPatterns = {
        "/*"
    },
    initParams = {
        @WebInitParam(name = "username", value = "Ramesh"),
        @WebInitParam(name = "password", value = "Pass@123")
    })
public class AuthFilter implements Filter {

    public void init(FilterConfig config) throws ServletException {
        // Get init parameter
        String username = config.getInitParameter("username");
        String password = config.getInitParameter("password");
        // Print the init parameter
        System.out.println("User name : " + username);
        System.out.println("Password : " + password);
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {

        // Log the current timestamp.
        System.out.println("Time " + new Date().toString());

        // Pass request back down the filter chain
        chain.doFilter(request, response);
    }

    public void destroy() {
        /*
         * Called before the Filter instance is removed from service by the web
         * container
         */
    }
}
Let's discuss how to use @WebFilter annotation with servlets.

Register a filter for a specific servlet

Let's register single servlet using servletNames attribute:
@WebFilter(servletNames = "SingleServlet")
public class SingleServlet implements Filter {
    // implements Filter's methods here...
}

Register a filter for multiple servlets

We can register multiple servlets using an array:
@WebFilter(servletNames = {"FirstServlet", "SecondServlet"})
public class SampleFilter implements Filter {
    // implements Filter's methods here...
}

Define additional information for the filter

In this following example, we will use "description", "filterName" attributes to specify the name and description of the filter:
@WebFilter(
        urlPatterns = "/users/*",
        filterName = "UserFilter",
        description = "Describe Filter"       
)
public class UserFilter implements Filter {
    // implements Filter's methods here...
}

Specify dispatcher types

In this following example, we will use "dispatcherTypes" attribute to specify the types of dispatcher (Request/Response) to which the filter applies:
@WebFilter(
        urlPatterns = "/user",
        dispatcherTypes = {DispatcherType.REQUEST, DispatcherType.FORWARD}
)
public class UserFilter implements Filter {
    // implements Filter's methods here...
}

Related Servlet Examples

Check out complete Servlet 4 tutorial at Servlet Tutorial

 Reference


Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments