🔍

Understanding Filters and Interceptors in Spring Boot

Apr 29, 2025

Lecture Notes: Filters versus Interceptors in Spring Boot

Introduction

  • Instructor: Shan
  • Previous video covered Spring Boot interceptors.
  • Topic: Differences between Filters and Interceptors.
  • Goal: Clarify doubts and help decide when to use a filter or an interceptor.

Definitions

  • Filter: Intercepts HTTP requests and responses before they reach the servlet.
  • Interceptor: Specific to Spring framework; intercepts HTTP requests and responses after servlet but before reaching the controller.

Request Handling in Spring Boot

  • Request flow:
    1. Servlet container (e.g., Tomcat) catches the request.
    2. Filters are applied in a chain before reaching the servlet.
    3. Dispatcher servlet determines the appropriate controller.
    4. Interceptors apply logic before reaching the controller.

Servlets

  • Servlet: A Java class accepting requests and returning responses.
  • Used for different tasks like handling REST APIs, SOAP APIs, etc.
  • In microservices (Spring Boot), need for multiple servlets is reduced.
  • Dispatcher servlet often handles all requests (/ mapping).

When to Use Filters vs. Interceptors

  • Filters:
    • Applied to all HTTP requests and responses, regardless of servlet.
    • Ideal for generic logic (e.g., security).
  • Interceptors:
    • Specific to Spring Boot's dispatcher servlet.
    • Ideal for logic specific to a particular servlet or application.

Implementation Details

Filters

  • Implement by creating a filter class with methods init, doFilter, and destroy.
  • Use doFilter to process requests and responses.
  • Sequence maintained via doFilter method.

Interceptors

  • Implement custom interceptors by configuring them in Spring Boot.
  • Methods include preHandle, postHandle, and afterCompletion.
  • preHandle can prevent further processing if it returns false.
  • Sequence is preHandle -> controller logic -> postHandle -> afterCompletion.

Code Examples

  • Demonstrated creating multiple filters and interceptors.
  • Showed how to control the order of execution and how requests and responses flow.

Conclusion

  • Filters and interceptors, though having access to request and response, should be chosen based on use case.
  • Filters are used for generic purposes, interceptors for application-specific logic.
  • Encourage further discussion for scenarios or additional insights on the topic.