Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

Servlets · Lesson 8

Servlet Filters

What Filters Are

A servlet filter intercepts requests and responses before or after a target servlet runs. Filters provide reusable cross-cutting behavior such as authentication checks, logging, compression, and security headers. They keep these concerns out of individual servlet classes.

Implementing a Filter

A filter receives a FilterChain, which represents the next step in processing. Calling chain.doFilter is what allows the target resource to run.

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/admin/*")
public class SecurityHeadersFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("X-Content-Type-Options", "nosniff");
        httpResponse.setHeader("Cache-Control", "no-store");
        chain.doFilter(request, response);
    }
}

Filter Flow

StageFilter actionExample
Before chainInspect or modify requestCheck an authorization header
Chain callContinue processingInvoke the servlet or next filter
After chainInspect or modify responseAdd a security header
Without chainStop processingReturn a 401 response

Common Mistake and Practices

Common Mistake: Forgetting chain.doFilter in a filter that should allow the request through. The request then appears to hang or returns a response without reaching its servlet.

  • Keep filters focused on one cross-cutting concern.
  • Register URL patterns narrowly.
  • Avoid expensive work on every request.
  • Return explicit status codes when rejecting a request.
  • Test filter ordering when several filters apply.

Real-World Use Case

An application places an authentication filter in front of /admin/*. It checks the current session before the request reaches any admin servlet, while a separate logging filter records request duration for all routes.

Quiz Check

Quick Knowledge Test

Loading quiz questions...