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
1
2
3
4
5
6
7
8
9
10
11
12
13
@Componentpublic class RequestLoggingInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {System.out.println("Incoming request: " + request.getMethod() + " " + request.getRequestURI());return true;}@Overridepublic 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.