SoFunction
Updated on 2025-05-21

Detailed explanation of Filter usage examples in java

Filter is one of the core components of Java Web development, used to intercept and process requests before they arrive at the servlet or responses return to the client. The following is a detailed analysis of its core functions, usage methods and actual scenarios:

1. Function and principle of Filter

Core role
Filter acts as an "intermediate layer" between requests and responses, and its main functions include:

  • Request preprocessing: such as unified encoding settings, sensitive word filtering, and permission verification.
  • Post-response processing: such as compressing the response content and adding security headers.
  • Resource interception control: Restrict access to specific resources according to rules (such as login verification).

How it works

  • Filter chain: Multiple Filters form chain processing in configuration order, requests pass through each Filter in sequence, and responses are forwarded in reverse.
  • Intercept time: The intercept request type can be configured (such asREQUESTFORWARD)。

2. Creation and configuration of Filter

Implementing Filter interface
Need to be implementedInterface and override three lifecycle methods:

public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig config) { /* Initialize the resource */ }
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
        throws IOException, ServletException {
        // Request processing logic (such as permission checking)        (req, res); // Release        // Response processing logic (such as logging)    }
    @Override
    public void destroy() { /* Release resources */ }
}

Configuration method

XML configuration ():

<filter>
    <filter-name>AuthFilter</filter-name>
    <filter-class></filter-class>
</filter>
<filter-mapping>
    <filter-name>AuthFilter</filter-name>
    <url-pattern>/secure/*</url-pattern>
    <dispatcher>REQUEST</dispatcher> <!-- Intercept request type -->
</filter-mapping>

Annotation configuration (recommended):

@WebFilter(urlPatterns = {"/secure/*"}, initParams = {@WebInitParam(name = "param", value = "value")})
public class AuthFilter implements Filter { /* ... */ }

3. The life cycle of Filter

init()method

  • Triggering time: Execute once when the server starts, to load initialization parameters or resources (such as database connections).
  • parameter:FilterConfigYou can obtain configuration information (such as<init-param>)。

doFilter()method

  • Core logic: execute every time the request meets the intercept path, and needs to be called()Release.
  • Intercept and modify: You can modify the request/response object here (such as rewriteHttpServletRequestWrapper)。

destroy()method

  • Triggering time: Executes when the server is shut down, used to free resources (such as closing the thread pool).

4. Detailed explanation of intercept path configuration

URL matching pattern
• Exact match:/loginIntercept only this path request.

• Directory Match:/admin/*Intercept/adminAll subpaths are below.

• Suffix matching:*.jspIntercept all JSP requests.

• Global Match:/*Intercept all requests.

Intercept type (Dispatcher)
REQUEST: Direct request (default).

FORWARD: Intercept forwarding requests (such as().forward())。

ERROR: Intercept the error page to jump.

5. Multiple Filter execution order

Configuration order rules
• XML configuration: Press<filter-mapping>Execute in the order of definition.

• Annotation configuration: By default, it is executed in dictionary order of class names (different containers may vary).

Sample flow

ask → Filter1 → Filter2 → Servlet → Filter2 → Filter1 → response

VI. Typical application scenarios

Unified encoding settings

public class EncodingFilter implements Filter {
    @Override
    public void doFilter(...) {
        ("UTF-8");
        ("UTF-8");
        (request, response);
    }
}

Permission control

public class LoginFilter implements Filter {
    @Override
    public void doFilter(...) {
        HttpSession session = ((HttpServletRequest) request).getSession();
        if (("user") == null) {
            ((HttpServletResponse) response).sendRedirect("/login");
        } else {
            (request, response);
        }
    }
}

Logging and performance monitoring

public class LogFilter implements Filter {
    @Override
    public void doFilter(...) {
        long startTime = ();
        (request, response);
        long duration = () - startTime;
        ("Request time consuming:" + duration + "ms");
    }
}

7. Things to note

Thread safety
Filter instances are singletons to avoid defining member variables in classes (if you need to share data, useThreadLocal)。

Performance optimization
• reducedoFilter()Blocking operations (such as remote calls) in combination with asynchronous processing if necessary.

• Set the interception path reasonably to avoid performance degradation caused by global interception.

Exception handling
existdoFilter()Catch exceptions in order to prevent filter chain interruption due to unhandled exceptions.

Summarize

Filter is the core tool for implementing global logic control in Java Web development. By flexibly configuring intercept paths and types, it can efficiently complete common functions such as encoding conversion, permission verification, and logging. Rationally designing the filter chain and execution sequence can significantly improve the maintainability and security of the application.

This is the end of this article about the detailed explanation of Filter usage examples in Java. For more related content on Java Filter usage, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!