🔍 1. Servlet Filters (javax.servlet.Filter)
🔧 Use Cases:
-
Logging request/response
-
Authentication
-
Compression
-
CORS
-
Request/response modification
-
Sanitizing inputs
📦 Example:
🚨 Characteristics:
-
Works on
HttpServletRequestandHttpServletResponse -
Can modify both request and response
-
Configured with
@Component,FilterRegistrationBean, orweb.xml -
Executes before DispatcherServlet
🔍 2. Spring Interceptors (HandlerInterceptor)
HandlerMapping).🔧 Use Cases:
-
Logging
-
Performance monitoring
-
Authorization checks
-
Pre/post controller logic
📦 Example:
And register it via:
🚨 Characteristics:
-
Only intercepts Spring-managed requests
-
Cannot modify response body directly
-
Does not apply to static resources unless configured
| Feature | Filter | Interceptor |
|---|---|---|
| Part of | Servlet API (javax.servlet) | Spring MVC (org.springframework.web.servlet) |
| Scope | Web container | Spring controller layer |
| Order of execution | Before DispatcherServlet | After DispatcherServlet, before Controller |
| Targets | All requests | Only Spring controller requests |
| Can modify response? | Yes (request/response body) | Limited (can redirect or stop request) |
| Exception handling | Can catch all exceptions | Limited to Spring controller scope |
| Use for auth/logging? | Best for general auth, logging, CORS | Best for controller-specific logging, auth |
| Registration | FilterRegistrationBean, @Component | WebMvcConfigurer#addInterceptors() |
| Goal | Use This |
|---|---|
Modify request/response streams Filter
CORS handling Filter
Authentication (general) Filter or Spring Security
Logging before/after controller Interceptor
Authorization (role-based) Interceptor or Spring Security
Request timing measurement Interceptor
🔹 1. What is a Filter and an Interceptor
| Aspect | Filter | Interceptor |
|---|---|---|
| Definition | Filter is a Servlet component used to intercept HTTP requests/responses before they reach the Spring Framework. | Interceptor is a Spring MVC component used to intercept requests after they enter Spring, specifically before and after controller execution. |
| API | javax.servlet.Filter | org.springframework.web.servlet.HandlerInterceptor |
| Scope | Servlet-level (external to Spring) | Spring MVC level (internal to Spring) |
| Order of Execution | Executes before DispatcherServlet | Executes after DispatcherServlet, and before/after controller methods |
🔹 2. Why Do We Use Filters and Interceptors?
| Goal | Use Filter | Use Interceptor |
|---|---|---|
| Authentication (JWT/Token) | ✅ Yes | ❌ No (too late) |
| Authorization (role check) | ❌ Not suitable | ✅ Yes (can check user roles, handler info) |
| Logging (all requests/responses) | ✅ Yes | ✅ Yes (controller-specific logging) |
| Modifying request/response | ✅ Yes | ❌ No (read-only access) |
| Request timing measurement | ❌ Not accurate | ✅ Yes |
| CORS handling | ✅ Yes | ❌ No |
| View model injection | ❌ No | ✅ Yes (via postHandle) |
No comments:
Post a Comment