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
In a Spring-mvc interceptor, how can I access to the handler controller method?
提问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 handler
to HandlerMethod
.
你可以投射Object handler
到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.
但是请注意,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.
在所有其他情况下,处理程序对象将指向控制器。网络上的大多数文档似乎都忽略了这个微妙的点。