Guide to Spring Boot Filter

In this Spring boot tutorial, we will learn to create, order and register servlet filters in different ways including Filter interface, @WebFilter annotation and inbuilt filter bean classes.

1. Introduction

In a web application, we must implement the javax.servlet.Filter interface to create filters that can be invoked for either the request to a resource, the response or both. To be more specific, we must write the filter logic in the doFilter() method of the implementation class.

Spring web module provides several inbuilt Filter implementations that we can use for specific purposes. These are abstract classes so we must extend and customize them to use in an application. Some of the most used Spring filters are:

  • AbstractRequestLoggingFilter: to perform logging operations before and after a request is processed.
  • CharacterEncodingFilter: to specify a character encoding for requests.
  • CorsFilter: to handle CORS pre-flight requests and to update the response.
  • OncePerRequestFilter: to guarantee a single execution per request dispatch, on any servlet container.

2. Defining a Filter

We can define a filter in Spring boot application in the following ways:

2.1. Implement Filter Interface

We can implement the Filter interface and override its methods to create the filter. Register the Filter with Spring context, we can use the @Component annotation.

@Component
public class LoggingFilter implements Filter {

  @Override
  public void doFilter(
      ServletRequest request,
      ServletResponse response,
      FilterChain chain) throws IOException, ServletException {

    log.info("Logging Filter Invoked...");
    chain.doFilter(request, response);
  }
}

2.2. Extend an Inbuilt Abstract Filter

Another way is to extend an inbuilt filter class. Note that we need to override doFilterInternal() method in this case.

@Component
public class SecurityFilter extends OncePerRequestFilter {

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

	  log.info("Security Filter Invoked...");
	  filterChain.doFilter(request, response);
	}
}

2.3. Using @WebFilter

The @WebFilter is part of Servlet 3.0 spec. The @WebFilter annotated classes can be automatically registered with an embedded servlet container. We can use the @WebFilter annotation in place of @Component annotation.

@WebFilter
public class AuditFilter implements Filter {

  @Override
  public void doFilter(
      ServletRequest request,
      ServletResponse response,
      FilterChain chain) throws IOException, ServletException {

    log.info("Audit Filter Invoked...");
    chain.doFilter(request, response);
  }
}

Note that we must add @ServletComponentScan annotation to enable scanning on @WebFilter annotated classes in embedded servers.

@SpringBootApplication
@ServletComponentScan
public class App {
  ...
}

3. Ordering Multiple Filters

The easiest way to order the filters is @Order annotation. Pass the order number as the annotation argument. For example:

@Order(1)
@Component
public class LoggingFilter implements Filter {
	...
}

@Order(2)
@Component
public class SecurityFilter implements Filter {
	...
}

@Order(3)
@Component
public class AuditFilter implements Filter {
	...
}

4. Filter with URL Patterns

By default, a filter is applied on all URLs in the application. If we want to restrict a filter to certain URLs then we must register the filter and URL pattern with FilterRegistrationBean.

In following example, we are configuring the SecurityFilter to be invoked only when URL pattern matches the pattern "/admin/*". We are also setting the precedence or order of filter in the filter chain.

@Configuration
public class AppConfig {
  @Bean
  public FilterRegistrationBean<SecurityFilter> filterRegistrationBean() {
    FilterRegistrationBean<SecurityFilter> registrationBean = new FilterRegistrationBean();

    registrationBean.setFilter(new SecurityFilter());
    registrationBean.addUrlPatterns("/admin/*");
    registrationBean.setOrder(2);
    return registrationBean;
  }
}

If we are using the @WebFilter annotation then we can pass the URL pattern directly into the annotation using the urlPatterns parameter.

@WebFilter(urlPatterns = "/admin/*")
public class AuditFilter implements Filter {
	...
}

Another way is to override the shouldNotFilter() method if we have extended any inbuilt Spring filter class.

@Component
public class SecurityFilter extends OncePerRequestFilter {

	...

	@Override
  protected boolean shouldNotFilter(HttpServletRequest request) {
      String path = request.getServletPath();
      return !path.matches("/admin/*");
  }
}

5. Disabling a Filter

If, for some reason, we have to disable the registration of a filter then we can use FilterRegistrationBean‘s setEnabled(false) method.

@Bean
public FilterRegistrationBean registration(AuditFilter filter) {
    FilterRegistrationBean registration = new FilterRegistrationBean(filter);
    registration.setEnabled(false);
    return registration;
}

6. Demo

For this demo, we have created all three filters discussed in tutorial i.e. LoggingFilter, SecurityFilter, AuditFilter and in same order. Initially there is no URL filtering so all filters will invoke in given order.

Hit the application root URL “/” and notice the logs.

2022-09-21 18:18:19.592  INFO 9148 --- [nio-8080-exec-4] c.h.app.config.LoggingFilter 	: Logging Filter Invoked...
2022-09-21 18:18:19.593  INFO 9148 --- [nio-8080-exec-4] c.h.app.config.SecurityFilter	: Security Filter Invoked...
2022-09-21 18:18:19.593  INFO 9148 --- [nio-8080-exec-4] c.h.app.config.AuditFilter		: Audit Filter Invoked...

Next we added the URL /admin/* matching to SecurityFilter and AuditFilter. This time, when we hit the root URL, only LoggingFilter is invoked.

2022-09-21 18:18:19.592  INFO 9148 --- [nio-8080-exec-4] c.h.app.config.LoggingFilter 	: Logging Filter Invoked...

Now hit a /admin/test URL and now we can see again all 3 filters being invoked as expected.

7. Conclusion

In this Spring boot tutorial, we learned to define, order and configure the servlet Filter using different ways. We also learned to disable a Filter using FilterRegistrationBean. Finally, we saw a demo of Spring Filters in action.

Happy Learning !!

Sourcecode on Github

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.