Spring Framework FAQ: Top Questions
23. What is the use of HandlerInterceptor in Spring MVC?
HandlerInterceptor
is used to intercept requests before they reach a controller or after the controller execution. It's useful for logging, auth, or metrics.
📘 Interface Methods:
preHandle()
– before controller method executionpostHandle()
– after controller but before view renderafterCompletion()
– after complete request
📥 Example:
public class LoggingInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
System.out.println("Request URL: " + req.getRequestURL());
return true;
}
}
🏆 Expected Output:
Logs each incoming URL before it reaches the controller.
🛠️ Use Cases:
- Authentication and authorization logic.
- Audit logging and metrics.