Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

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 execution
  • postHandle() – after controller but before view render
  • afterCompletion() – 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.