0 day streak
java / intermediate
Snippet

Intercepting Requests with HandlerInterceptor

A HandlerInterceptor allows you to execute logic before or after a request reaches a controller. This is ideal for logging, authentication checks, or adding common headers without cluttering controller methods.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
@Component
public class RequestLoggingInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
System.out.println("Incoming request: " + request.getMethod() + " " + request.getRequestURI());
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
System.out.println("Request processed successfully");
}
}
spring
Breakdown
1
preHandle
Executes before the controller method; returns false to block the request.
2
postHandle
Executes after the controller method but before view rendering.
3
HttpServletRequest
Provides access to headers, parameters, and HTTP methods.