Creating a custom request filter in Spring Boot is a relatively simple process that can be accomplished by following a few basic steps.

  • Create a new class that extends the OncePerRequestFilter class. This ensures that the filter will be executed only once per incoming request.

  • In your filter class, override the doFilter method. This method is called for each request that is sent to your application. In this method, you can perform any logic you want to execute for the filter, such as logging, authentication, or validation.

  • Annotate your filter class with @Component so that Spring Boot can automatically discover and register it as a filter.

  • Use the @Order annotation to specify the order in which the filter should be executed relative to other filters. Filters with a lower order value will be executed first.

@Component
@Order(1)
public class MyCustomFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain filterChain
    ) throws ServletException, IOException {
    
        // do some stuff

        filterChain.doFilter(request, response);
    }
}

To apply the filter to specific URLs, use a @Bean annotation to assign the filter only to request that meet criteria. For example, the code below attaches the MyCustomFilter.class only to request that match the /api/* patch pattern.

@Component
@Order(1)
public class MyCustomFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain filterChain
        ) throws ServletException, IOException {
    
        // do some stuff

        filterChain.doFilter(request, response);
    }
    
    @Bean
    public FilterRegistrationBean<MyCustomFilter> myCustomerFilter()
    {
        FilterRegistrationBean<MyCustomFilter> bean = new FilterRegistrationBean<>();
 
        bean.setFilter(new MyCustomFilter());
        bean.addUrlPatterns("/api/*");
 
        return bean;
    }

}