Common Filters in the Java EE Filter API

Common Filters in the Java EE Filter API

In Java web development, Servlet Filters are one of the key components for handling requests and responses. Unlike listeners, filters can intercept various stages of HTTP requests or responses, thereby enabling preprocessing and postprocessing of resources. Their lifecycle is managed by the container and follows a strict sequence: creation, initialization, invocation of the doFilter method, and destruction.

The core function of a filter lies in its ability to "intercept." When a client initiates a request, it passes sequentially through every filter in the configured chain. Similarly, after the server generates a response, it traverses the filter chain in reverse order for corresponding processing. This bidirectional control mechanism allows developers to insert generic code before and after business logic execution, such as logging, parameter validation, or security authentication.
A standard Servlet Filter class must inherit from javax.servlet.Filter (or jakarta.servlet.Filter in Java EE/EE8+) and implement its core method doFilter(ServletRequest request, ServletResponse response). In addition to these two required methods, the container automatically invokes the init() and destroy() methods to manage the filter's lifecycle.

In practical development, filters are commonly used in the following scenarios:

  • Logging: Print access information before the request reaches business logic or output timing statistics after the response is returned;
  • Character Encoding Unification: Force request parameters to be parsed as UTF-8 format to avoid garbled text issues;
  • Security Interception: Check user identity or token validity and deny unauthorized access;
  • Performance Monitoring: Record metrics such as interface call times and exception counts.

Below is a basic filter example code snippet (based on Java EE):

import javax.servlet.*;
import java.io.IOException;

public class LoggingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Initialization logic here if needed
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, 
                         FilterChain chain) throws IOException, ServletException {
        System.out.println("Request started: " + request.getRequestURI());
        
        // Continue processing the next filter in the chain or the target resource
        chain.doFilter(request, response);

        System.out.println("Response ended");
    }

    @Override
    public void destroy() {
        // Cleanup logic here if needed
    }
}

Configuration and Deployment Considerations for web.xml

When registering a filter in web.xml, it is mandatory to explicitly specify its name, implementation class, and mapping rules. The <filter-mapping> tag can define which URL paths or HTTP methods (such as GET/POST) the filter applies to. Additionally, priority can be set; a smaller numerical value indicates earlier execution order.

Please note the following:

  • If web.xml is not configured, annotations must be used for declaration;
  • Dependencies may exist between multiple filters, so the calling order should be designed reasonably;
  • In modern frameworks like Spring Boot, it is recommended to use @WebFilter or automatic scanning mechanisms instead of traditional XML configuration.

Best Practices and Common Pitfalls

To avoid code duplication and improve maintainability, it is advisable to encapsulate generic logic into independent classes and reuse them via dependency injection. At the same time, be careful to avoid time-consuming operations within filters (such as database queries), as this could block the entire request chain and degrade performance. For scenarios requiring cross-domain handling, also pay attention to CORS policy configuration location—it should typically be handled uniformly at the outermost layer or a specific gateway layer rather than scattered across various business filters.

By designing and using Servlet Filters reasonably, developers can build more robust, secure, and easily extensible web application architectures.