Sobes.tech
Middle

What do you know about servlet filters?

sobes.tech AI

Answer from AI

Servlet filters allow intercepting and processing incoming requests and outgoing responses in a web application before they reach the servlet, and after the servlet has finished processing. They are used for common logic such as authentication, logging, data compression, or modifying request/response content.

Filters implement the javax.servlet.Filter interface and have three main methods:

  1. init(FilterConfig filterConfig): Called once during filter initialization. Used for setup.
  2. doFilter(ServletRequest request, ServletResponse response, FilterChain chain): The main method that performs the filter logic. The FilterChain parameter allows passing the request/response to the next filter in the chain or to the final servlet using chain.doFilter().
  3. destroy(): Called once before the filter is destroyed. Used for resource cleanup.

Filter configuration is done either through web.xml or using the @WebFilter annotation (since Servlet 3.0).

Example from web.xml:

<filter>
    <filter-name>AuthenticationFilter</filter-name>
    <filter-class>com.example.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>AuthenticationFilter</filter-name>
    <url-pattern>/secure/*</url-pattern>
</filter-mapping>

Example with annotation:

@WebFilter("/secure/*")
public class AuthenticationFilter implements Filter {
    // ... implementation of init, doFilter, destroy
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // Authentication logic
        if (isAuthenticated(request)) {
            chain.doFilter(request, response); // Passes further down the chain
        } else {
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    }

    // ... init and destroy methods
}

The filter chain (FilterChain) allows applying multiple filters sequentially to a single request/response. The order of filter execution is determined in web.xml or via annotation attributes.

Differences from Interceptors in Spring/Java EE:

  • Servlet filters operate at the container and web architecture level.
  • Interceptors (e.g., CDI Interceptors or Spring MVC Interceptors) work at a higher level of abstraction (components, methods, or controllers).

Filters are a powerful tool for implementing cross-functional logic that should be applied to many requests or responses in a web application without duplication in each servlet.