Sobes.tech
Middle

What is the difference between Filters, Interceptors, and Listeners in Spring?

sobes.tech AI

Answer from AI

  • Filters (Spring Web): Intercept requests and responses at the servlet level. Used for modifying requests/responses, authentication, authorization, logging before the request reaches the controller. Applied to URL patterns.

  • Interceptors (Spring MVC): Intercept requests at the Spring MVC level. Work after Filters but before the controller processes the request. Allow actions before (preHandle), after (postHandle), and after completion (afterCompletion). Used for model manipulation, access control at controller level. Applied to controller methods.

  • Listeners (Spring Context): React to events in the Spring context. Allow actions on startup or shutdown, on specific event types. Used for resource initialization, cleanup, or tasks on application state changes. Work independently of web requests. Implement ApplicationListener.

Here's a tabular comparison:

Feature Filters Interceptors Listeners
Level Servlet Spring MVC Spring Context
When they run Before and after servlet Before, after controller, and completion On event occurrence
Applied to URL patterns Controller methods Event types
Purpose Modify request/response, authentication Model manipulation, controller-level authorization React to context events
Interface javax.servlet.Filter HandlerInterceptor ApplicationListener