我正在尝试创建一个拦截器,使当前 Controller 名称和操作(方法)名称可用于我的 View 。这似乎在大多数时候都很有效。
public class BaseInterceptor extends HandlerInterceptorAdapter {
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
String controllerName = "";
String actionName = "";
if( handler instanceof HandlerMethod ) {
// there are cases where this handler isn't an instance of HandlerMethod, so the cast fails.
HandlerMethod handlerMethod = (HandlerMethod) handler;
controllerName = handlerMethod.getBean().getClass().getSimpleName().replace("Controller", "");
actionName = handlerMethod.getMethod().getName();
}
modelAndView.addObject("controllerName", controllerName );
modelAndView.addObject("actionName", actionName );
}
}
唯一一次这不起作用是当我使用 Spring Security 登录时。发生这种情况时,我得到一个代理包装器作为 Controller 名称。有没有办法获得实际的 Controller 名称?
Post$$EnhancerBySpringCGLIB$$3ef51261
最佳答案
无论您是否使用 spring security,这都适用于获取 Controller 名称。
controllerName = handlerMethod.getBeanType().getSimpleName().replace("Controller", "");
关于java - Spring 底座拦截器 : Get Controller & Method Name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34792999/