To implement a filter in Spring Boot, create a class that implements the javax.servlet.Filter (or jakarta.servlet.Filter for Spring Boot 3+) interface and annotate it with @Component. This allows you to intercept every incoming HTTP request before it reaches your controllers, enabling you to perform tasks like authentication checks, logging, or modifying request headers.

What You'll Need

  • A working Spring Boot project (initialized via Spring Initializr or an IDE).
  • Java Development Kit (JDK) installed.
  • An IDE (such as IntelliJ IDEA, Eclipse, or VS Code).
  • Basic knowledge of Java and the Spring Framework.

Step-by-Step

  1. Choose your Servlet API: Determine if you are using Spring Boot 2 (which uses javax.servlet) or Spring Boot 3 (which uses jakarta.servlet). Ensure your imports match your project version.
  2. Create the Filter Class: Create a new Java class. Implement the Filter interface. This interface requires you to override three methods: init(), doFilter(), and destroy().
  3. Annotate as a Component: Add the @Component annotation to the class. This tells Spring to automatically detect the filter and register it in the filter chain for all incoming requests.
  4. Implement the doFilter Logic: Inside the doFilter method, write the logic you want to execute before the request reaches the controller.
    • To perform an action before the request: Write your code before calling chain.doFilter(request, response).
    • To perform an action after the request: Write your code after calling chain.doFilter(request, response).
  5. Pass the Request Along: Crucially, you must call filterChain.doFilter(request, response). If you omit this line, the request will stop at the filter and never reach your REST controller, resulting in a blank response or a timeout.
  6. (Optional) Define Filter Order: If you have multiple filters, use the @Order annotation (from org.springframework.core.annotation) to specify the execution sequence. A lower number (e.g., @Order(1)) runs earlier than a higher number.
  7. (Optional) Restrict URL Patterns: If you do not want the filter to run on every single request, remove the @Component annotation and instead create a FilterRegistrationBean bean in a configuration class. In that bean, use addUrlPatterns("/api/*") to limit the filter to specific paths.

Common Mistakes

  • Forgetting the Filter Chain: The most frequent error is forgetting to call chain.doFilter(request, response). This effectively "swallows" the request, and the client receives no response from the server.
  • Incorrect Package Imports: Mixing javax.servlet and jakarta.servlet will cause compilation errors or runtime failures in Spring Boot 3. Always stick to the version compatible with your Spring Boot release.
  • Overloading the Filter: Putting heavy business logic or complex database queries inside a filter can significantly slow down every single request to your application. Keep filters lean.
  • Infinite Loops: If a filter redirects a request to a URL that is also covered by the same filter, you may create an infinite redirect loop.

Tips

  • Use for Cross-Cutting Concerns: Filters are ideal for "cross-cutting concerns" such as adding a Correlation ID to logs, validating a custom API key in the header, or handling CORS (Cross-Origin Resource Sharing).
  • Logging Strategy: When logging in a filter, use a unique identifier (like a UUID) for each request. This allows you to trace a single request's journey through the filter and into the controller in your log files.
  • Filter vs. Interceptor: Use a Filter for low-level HTTP tasks (like modifying the raw request/response). Use a HandlerInterceptor if you need access to the Spring-specific "Handler" (the method in the controller) that is about to be executed.

Troubleshooting

If your filter is not executing or causing errors, try these steps in order:

  1. Check the Console Logs: Look for BeanCreationException or ClassNotFoundException. This usually indicates a mismatch between the Servlet API version and your Spring Boot version.
  2. Verify the Annotation: Ensure @Component is present. If you are using a FilterRegistrationBean, ensure the configuration class is annotated with @Configuration.
  3. Check URL Patterns: If you used a registration bean, double-check the path patterns. A typo in /api/* (like /api/) can prevent the filter from triggering on specific endpoints.
  4. Inspect the Filter Chain Order: If you have multiple filters, one might be throwing an exception or returning a response before the request ever reaches your specific filter. Temporarily remove other filters to isolate the issue.

Frequently Asked Questions

Can I access the request body inside a filter?

Yes, but be careful. The request input stream can only be read once. If you read the body in a filter, the controller will find the stream empty. To solve this, you must wrap the request in a ContentCachingRequestWrapper.

What is the difference between a Filter and a Spring Interceptor?

Filters are part of the Servlet container and operate outside the Spring DispatcherServlet. Interceptors are Spring-managed and have access to the Spring context and the specific handler method being called.

How do I skip a filter for specific endpoints?

The easiest way is to use a FilterRegistrationBean and define specific urlPatterns. Alternatively, you can check the request URI inside the doFilter method and call chain.doFilter immediately if the URI matches your exclusion list.

Can a filter modify the response body?

Yes, but it requires wrapping the response in a ContentCachingResponseWrapper. This allows you to capture the output, modify it, and then write the modified version back to the original response stream.

Do filters run for static resources?

By default, if you use @Component, the filter runs for all requests, including those for static assets like CSS or JS files. Use a FilterRegistrationBean to restrict the filter to only your API endpoints.