In a Spring-mvc interceptor I want to access to the handler controller method
public class CustomInterceptor implements HandlerInterceptor {
public boolean preHandle(
HttpServletRequest request,HttpServletResponse response,
Object handler) {
log.info(handler.getClass().getName()); //access to the controller class
//I want to have the controller method
...
return true;
}
...
}
I have found :
how-to-get-controller-method-name-in-spring-interceptor-prehandle-method
But it only work around. I want the method name to access to the annotation.
Spring HandlerInterceptor declares three methods based on where we want to intercept the HTTP request. boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler): This method is used to intercept the request before it's handed over to the handler method.
Each handler interceptor must implement the HandlerInterceptor interface, which contains three callback methods for you to implement: preHandle() , postHandle() , and afterCompletion() .
annotation. RequestMapping annotation is used to map web requests onto specific handler classes and/or handler methods. @RequestMapping can be applied to the controller class as well as methods. Today we will look into various usage of this annotation with example and other annotations @PathVariable and @RequestParam .
Spring Handler Interceptor The HandlerInterceptor contains three main methods: prehandle() – called before the execution of the actual handler. postHandle() – called after the handler is executed. afterCompletion() – called after the complete request is finished and the view is generated.
HandlerInterceptors will only provide you access to the HandlerMethod IF you have registered your interceptors like so :
@EnableWebMvc
@Configuration
public class InterceptorRegistry extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(org.springframework.web.servlet.config.annotation.InterceptorRegistry registry) {
registry.addInterceptor(new InternalAccessInterceptor());
registry.addInterceptor(new AuthorizationInterceptor());
}
}
In all other cases, the handler object will point to the controller. Most documentation on the web seemed to have missed this subtle point.
You can cast the Object handler
to HandlerMethod
.
HandlerMethod method = (HandlerMethod) handler;
Note however that the handler
argument passed to preHandle
is not always a HandlerMethod
(careful with ClassCastException
). HandlerMethod
then has methods you can use to get annotations, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With