java 在 Spring-mvc 拦截器中,如何访问处理程序控制器方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17575623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:21:54  来源:igfitidea点击:

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

javaspring-mvcinterceptor

提问by Troncador

In a Spring-mvc interceptor I want to access to the handler controller method

在 Spring-mvc 拦截器中,我想访问处理程序控制器方法

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.

但它只能解决。我希望方法名称可以访问注释。

回答by Sotirios Delimanolis

You can cast the Object handlerto HandlerMethod.

你可以投射Object handlerHandlerMethod.

HandlerMethod method = (HandlerMethod) handler;

Note however that the handlerargument passed to preHandleis not always a HandlerMethod(careful with ClassCastException). HandlerMethodthen has methods you can use to get annotations, etc.

但是请注意,handler传递给的参数preHandle并不总是 a HandlerMethod(小心ClassCastException)。HandlerMethod然后有可用于获取注释等的方法。

回答by dr.house

HandlerInterceptors will only provide you access to the HandlerMethod IF you have registered your interceptors like so :

如果您像这样注册了拦截器,HandlerInterceptors 只会为您提供对 HandlerMethod 的访问:

@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.

在所有其他情况下,处理程序对象将指向控制器。网络上的大多数文档似乎都忽略了这个微妙的点。