java / expert
Snippet
Granular Pre-Processing with HandlerInterceptor
HandlerInterceptors provide a way to apply logic before it reaches the Controller but after the Servlet Filter chain. This is ideal for logic that requires knowledge of the Spring Handler (e.g., checking annotations on the controller method).
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Componentpublic class RateLimitingInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception {String apiKey = request.getHeader("X-API-KEY");if (!limiter.tryConsume(apiKey)) {response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());return false;}return true;}}
spring
Breakdown
1
return false;
Stops the execution of the request, preventing it from reaching the controller.
2
Object handler
The target handler (controller method) that will process the request if execution continues.