Spring MVC
Interceptor
Filter
Web Development
Java

Difference between Interceptor and Filter in Spring MVC

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Difference between Interceptor and Filter in Spring MVC

In Spring MVC, both interceptors and filters play significant roles in request processing. They enable handling cross-cutting concerns like logging, authentication, and authorization. While they are often used interchangeably, they address different concerns and work at different levels of request lifecycle. Understanding their differences and applications helps in choosing the right mechanism for a particular requirement.

1. Functionality and Purpose

  • Filter:
    • Filters are a part of the Servlet API and operate at a lower level. They are tied to the Servlet lifecycle and can influence the request and response.
    • Filters are mainly utilized to process incoming requests and responses before they reach their desired target (e.g., Servlets, JSPs).
    • They are useful for tasks like logging, authentication, and response compression.
  • Interceptor:
    • Interceptors are specific to Spring MVC which works at a higher abstraction level. They can be used to pre-process and post-process the requests.
    • They are primarily used for cross-cutting concerns that do not belong to the core business logic, such as authentication, validation, and session logging.
    • An interceptor can intercept actions and expects the execution to be handled down the stack.

2. Lifecycle and Execution

  • Filter:
    • Implement the javax.servlet.Filter interface.
    • The typical method sequence is doFilter(), and it wraps the request with a FilterChain.
    • Filters handle both request and response objects.
    • The scope of execution includes the whole servlet context.
  • Interceptor:
    • Implement the HandlerInterceptor interface in Spring MVC.
    • Involves three main methods: preHandle(), postHandle(), and afterCompletion().
    • Interceptors are executed only after the DispatcherServlet routes the request to the appropriate handler.

3. Order of Execution

  • Filter:
    • Filters are processed before any servlet or Spring brings the request for processing.
    • They can execute in a defined order using @Order or <filter-mapping> in web.xml.
  • Interceptor:
    • Interceptors are invoked after filters, within the Spring context.
    • Interceptors can be mapped to specific handler mappings, allowing precise execution control using <mvc:interceptor> or @InterceptorRegistry.

4. Technical Examples

  • Filter Example:
java
1  import javax.servlet.Filter;
2  import javax.servlet.FilterChain;
3  import javax.servlet.FilterConfig;
4  import javax.servlet.ServletException;
5  import javax.servlet.ServletRequest;
6  import javax.servlet.ServletResponse;
7  import java.io.IOException;
8
9  public class SimpleFilter implements Filter {
10
11      @Override
12      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
13              throws IOException, ServletException {
14          System.out.println("Request received in Filter");
15          chain.doFilter(request, response);
16          System.out.println("Response sent in Filter");
17      }
18
19      @Override
20      public void init(FilterConfig filterConfig) throws ServletException {}
21
22      @Override
23      public void destroy() {}
24  }
  • Interceptor Example:
java
1  import org.springframework.web.servlet.HandlerInterceptor;
2  import javax.servlet.http.HttpServletRequest;
3  import javax.servlet.http.HttpServletResponse;
4  import org.springframework.web.servlet.ModelAndView;
5
6  public class SimpleInterceptor implements HandlerInterceptor {
7
8      @Override
9      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
10          System.out.println("Request received in Interceptor - preHandle");
11          return true;
12      }
13
14      @Override
15      public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
16          System.out.println("Request processed in Interceptor - postHandle");
17      }
18
19      @Override
20      public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
21          System.out.println("Request completed in Interceptor - afterCompletion");
22      }
23  }

5. Use Cases

  • Filters are preferable when dealing with low-level tasks such as:
    • Handling generic tasks like access logging, performance monitoring.
    • Modifying request and response headers globally.
    • Integrating with third-party libraries requiring servlet filters.
  • Interceptors are ideal for higher-level processing like:
    • Handling multi-module systems with specific flow.
    • Implementing pre-processing logic before delegating to a controller.
    • Modifying model attributes on the fly or Internationalization.

Table Summarizing Key Differences

FeatureFilterInterceptor
API LevelServlet APISpring MVC
ImplementationImplements javax.servlet.FilterImplements HandlerInterceptor
Abstraction LevelLow-level, servlet specificationHigh-level, framework-specific
Order of ExecutionBefore servlets and interceptorsAfter filters but before handler
Execution ContextWhole servlet contextBound within Spring MVC context
ManipulationRequest and ResponseRequest only
Typical Use CasesLogging, authentication, response mod.Validation, authorization, pre/post-processing

Conclusion

Choosing between filters and interceptors depends on the specific needs of the application. Filters give broad, encompassing capabilities at a low level, ideal for tasks tied closely to the request-response lifecycle. In contrast, interceptors afford higher-level abstraction closely integrated with the handling of requests within the Spring MVC context, offering more control over framework-specific operations.

Both can be used together to manage different concerns effectively, offering a fine-grained control over web application behavior. Understanding their functionalities ensures a robust implementation strategy suited to your application's architecture and design goals.


Course illustration
Course illustration

All Rights Reserved.