繁体   English   中英

如何从Spring HandlerInterceptor中查找Handler上调用的方法?

[英]How can I lookup the method being called on a Handler from a Spring HandlerInterceptor?

我有一个Spring HandlerInterceptor拦截我的应用程序中的前端URL(/ app / *)。 我想确定要在HandlerInterceptor中调用Handler中的哪个动作方法。 有没有办法查看,我是否需要向拦截器注入一些可以根据请求的路径查找的内容?

拦截器是这样的:

public class PageCacheInterceptor implements HandlerInterceptor {...}

它映射如下:

<mvc:interceptors>
    <bean class="com.example.web.interceptors.PageCacheInterceptor" />
</mvc:interceptors>

背景(因为我知道你会问!)。 我正在为我的应用添加简单的页面缓存,并希望在控制器中的每个合适的方法上使用@Cacheable之类的注释。 然后,拦截器可以根据创建响应的操作确定是否缓存响应。

例如:

@RequestMapping(value = "", method = RequestMethod.GET)
@Cacheable(events={Events.NEW_ORDER,Events.NEW_STAT})
public String home(Model model) {...}

事件是导致缓存失效的事件。 例如,/ widget / list动作会使其缓存的响应被保存的新窗口小部件无效。

编辑:我已经升级到最新的Spring 3.1 M2,因为这篇博文暗示了我需要的功能,但是不清楚是否需要注入这些新类或对它们进行子类化。 有没有人用它们来拦截拦截器中的HandlerMethod?

好的,所以解决方案实际上非常简单:

1)升级到Spring 3.1

2) RTFM (正确)

例如,HandlerInterceptor可以将处理程序从Object转换为HandlerMethod,并可以访问目标控制器方法,其注释等。

3)在Interceptor中将处理程序对象强制转换为HandlerMethod。

然后你可以做这样的事情:

    HandlerMethod method = (HandlerMethod) handler;
    Cacheable methodAnnotation = method.getMethodAnnotation(Cacheable.class);
    if (methodAnnotation != null) {
        System.out.println("cacheable request");
    }
@Override 
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 
System.out.println("Pre-handle"); 
HandlerMethod hm=(HandlerMethod)handler; 
Method method=hm.getMethod(); if(method.getDeclaringClass().isAnnotationPresent(Controller.class)){
 if(method.isAnnotationPresent(ApplicationAudit.class))
{ 
System.out.println(method.getAnnotation(ApplicationAudit.class).value()); 
request.setAttribute("STARTTIME",System.currentTimemillis());
 }
} 
return true; 
} 

这篇文章有更多细节,希望这有助于http://www.myjavarecipes.com/spring-profilingaudit-using-mvc-filters/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM