Using Servlet Filter as a Spring bean with DelegatingFilterProxy

[Updated: Jul 14, 2017, Created: Jul 14, 2017]

DelegatingFilterProxy can be used as a proxy for a standard Servlet Filter.

DelegatingFilterProxy itself is a Servlet Filter which delegates to a specified Spring-managed bean that implements the Filter interface.

We need to set DelegatingFilterProxy's "targetBeanName" property as the target bean name (the bean which implements Filter interface).

Let's see an example how to use it.

Example

A bean implementing Servlet Filter

@Component("myTestFilter")
public class MyFilter implements Filter {
  
  @Autowired
  private MyService myService;
  
  @Override
  public void init (FilterConfig filterConfig) throws ServletException {
  }
  
  @Override
  public void doFilter (ServletRequest request, ServletResponse response,
                        FilterChain chain)
            throws IOException, ServletException {
      System.out.println("-- In MyFilter --");
      HttpServletRequest req = (HttpServletRequest) request;
      myService.doSomething(req);
      chain.doFilter(request, response);
  }
  
  @Override
  public void destroy () {
      
  }
}
@Component
public class MyService {

  public void doSomething (HttpServletRequest req) {
      System.out.println("In MyService: " + req.getRequestURI());
  }
}

Java Config class

@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig {
}

Registering DelegatingFilterProxy

public class AppInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {
    .............
  @Override
  protected Filter[] getServletFilters () {
      DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
      filterProxy.setTargetBeanName("myTestFilter");
      return new Filter[]{filterProxy};
  }
    .............
}

A Controller

@Controller
@RequestMapping("/**")
public class MyController {
  
  @RequestMapping
  @ResponseBody
  public String handleRequest () {
      System.out.println("-- handling request in controller --");
      return "dummy response";
  }
}

Output

Output on server console:

-- In MyFilter --
In MyService: /app
-- handling request in controller --

Example Project

Dependencies and Technologies Used :

  • spring-webmvc 4.3.9.RELEASE: Spring Web MVC.
  • spring-test 4.3.9.RELEASE: Spring TestContext Framework.
  • javax.servlet-api 3.1.0 Java Servlet API
  • junit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • JDK 1.8
  • Maven 3.3.9

Using Servlet Filter as Spring Bean Select All Download
  • servlet-filter-as-spring-bean
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also