Spring Filter vs Interceptor: When to Use Each in Java Web Apps
This guide explains the concepts, implementation steps, configuration examples, and key differences between Servlet Filters and Spring MVC Interceptors, helping developers choose the right tool for request preprocessing, logging, and access control in Java web applications.
Understanding Servlet Filters
Servlet Filters belong to the Servlet specification and act as an enhanced version of a servlet by implementing the javax.servlet.Filter interface. They are typically used for request preprocessing such as authentication, logging, character encoding, and decoding.
When a request arrives, the container initializes the filter once, then for each request the doFilter method can inspect or modify the ServletRequest and ServletResponse. After the downstream servlet processes the request, the filter can perform post‑processing before the response is sent back.
The filter lifecycle consists of three methods: void init(FilterConfig filterConfig) – called once during container startup for initialization.
void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)– contains the core filtering logic; calling chain.doFilter() passes control to the next filter or servlet. void destroy() – invoked before the filter is removed, allowing resource cleanup.
Example implementation:
public class LogFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("Filter 初始化");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
System.out.println("Filter 预处理");
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("Filter 后处理");
}
@Override
public void destroy() {
System.out.println("容器销毁");
}
}In a traditional web project the filter is declared in web.xml:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>com.secbro2.learn.filter.LogFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>For Spring Boot projects, the filter can be registered as a Spring bean:
@Configuration
public class FilterConfig {
@Resource
private LogFilter logFilter;
@Bean
public FilterRegistrationBean<Filter> registerAuthFilter() {
FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
registration.setFilter(logFilter);
registration.addUrlPatterns("/*");
registration.setName("authFilter");
// Smaller order value means higher precedence
registration.setOrder(1);
return registration;
}
}Running a controller with this filter produces the following console output:
Filter 初始化
---以上为启动项目时打印---
Filter 预处理
Controller中处理业务逻辑
Filter 后处理
---以上为访问Controller时打印---
容器销毁
---以上为关闭服务时打印---Understanding Spring MVC Interceptors
Interceptors are part of Spring's AOP support and implement the org.springframework.web.servlet.HandlerInterceptor interface. They can execute code before a controller method, after the method but before view rendering, and after the complete request has finished.
The three methods are:
boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)– called before controller execution; returning false aborts the request.
void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)– called after controller execution but before view rendering; executed in reverse order of registration.
void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)– called after the view is rendered, useful for resource cleanup.
Example interceptor:
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
System.out.println("Interceptor preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
System.out.println("Interceptor postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
System.out.println("Interceptor afterCompletion");
}
}Register the interceptor with Spring MVC:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Resource
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
}
}When a request passes through this interceptor, the console logs:
Interceptor preHandle
Controller中处理业务逻辑
Interceptor postHandle
Interceptor afterCompletionKey Differences Between Filters and Interceptors
1. Scope and Specification : Filters are defined by the Servlet specification and only work within a servlet container. Interceptors are Spring components and can be used in web, desktop, or other Spring‑based applications.
2. Resource Access : Interceptors can autowire any Spring bean (services, data sources, transaction managers). Filters cannot directly access Spring‑managed resources.
3. Granularity : Filters operate around the entire servlet request/response lifecycle. Interceptors can hook into specific controller method execution, allowing pre‑ and post‑processing at a finer level.
4. Implementation Mechanism : Filters rely on callback methods defined by the servlet API, while interceptors use Java reflection and Spring’s handler mapping.
5. When to Use : Use a filter when you need to manipulate or block the raw request/response (e.g., character encoding, security headers). Use an interceptor when you need to interact with Spring beans or perform logic tied to controller execution (e.g., permission checks, logging business actions).
Conclusion
Both Servlet Filters and Spring MVC Interceptors are powerful tools for request handling. Understanding their lifecycle, capabilities, and integration points enables developers to choose the appropriate mechanism: filters for low‑level, container‑wide concerns, and interceptors for Spring‑aware, fine‑grained processing.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Senior Brother's Insights
A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
