In a Spring-mvc interceptor, how can I access to the handler controller method?

爱⌒轻易说出口 提交于 2019-11-27 06:02:39

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/17575623/in-a-spring-mvc-interceptor-how-can-i-access-to-the-handler-controller-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!