@WebFilter Annotation Example (Jakarta EE)

In this blog post, we'll explore the @WebFilter annotation, which is used to define a filter in a web application. Filters are used to perform filtering tasks on either the request to a resource, the response from a resource, or both. The @WebFilter annotation is part of the Jakarta Servlet API and eliminates the need for configuring filters in the web.xml file.

Step 1: Add Servlet Dependency to pom.xml

First, we need to add the Jakarta Servlet dependency to our pom.xml file. Here, we are using version 6.1.0.

<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>
        <!-- Jakarta Servlet dependency -->
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>java-servlet-tutorial</finalName>
    </build>
</project>

Step 2: Create Filter Using @WebFilter

Let's create a simple filter that logs request information.

LoggingFilter.java

package net.javaguides.servlet.tutorial.httpservlet;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class LoggingFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Filter initialization code, if necessary
    }

    @Override
    public void doFilter(jakarta.servlet.ServletRequest request, jakarta.servlet.ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        System.out.println("Logging Request: " + req.getMethod() + " " + req.getRequestURI());
        chain.doFilter(request, response);
        System.out.println("Logging Response: " + res.getContentType());
    }

    @Override
    public void destroy() {
        // Cleanup code, if necessary
    }
}

In this example, the LoggingFilter class implements the Filter interface and is annotated with @WebFilter. The urlPatterns attribute specifies that the filter applies to all URLs.

Commonly Used Attributes of @WebFilter

The @WebFilter annotation provides several attributes for configuring filters:

  • filterName: The name of the filter.
  • urlPatterns: Specifies the URL patterns to which the filter applies.
  • servletNames: Specifies the servlet names to which the filter applies.
  • dispatcherTypes: Specifies the dispatcher types (REQUEST, FORWARD, INCLUDE, ERROR, ASYNC).
  • initParams: Specifies the initialization parameters for the filter.

Additional Examples of @WebFilter

Filter with Specific URL Patterns

@WebFilter(urlPatterns = {"/admin/*", "/user/*"})
public class AuthenticationFilter implements Filter {
    // Filter implementation
}

Filter with Initialization Parameters

@WebFilter(
    urlPatterns = "/secured/*",
    initParams = {
        @WebInitParam(name = "param1", value = "value1"),
        @WebInitParam(name = "param2", value = "value2")
    }
)
public class ConfigurableFilter implements Filter {
    // Filter implementation
}

Filter with Dispatcher Types

@WebFilter(
    urlPatterns = "/*",
    dispatcherTypes = {DispatcherType.REQUEST, DispatcherType.FORWARD}
)
public class CustomDispatcherFilter implements Filter {
    // Filter implementation
}

Conclusion

In this blog post, we demonstrated the usage of the @WebFilter annotation to define filters in a web application. We covered the basic usage and provided additional examples to illustrate how to create filters with different configurations. The @WebFilter annotation simplifies filter configuration by allowing filters to be defined directly in the Java class.

References

Related Servlet Posts

Comments