2011-09-03 73 views
5

我有一个Spring HandlerInterceptor拦截我的应用程序(/ app/*)中的前端URL。我想要确定HandlerInterceptor中将要从Handler中调用哪个操作方法。有没有办法查看这个问题,我是否需要在拦截器中注入一些可以根据请求路径查找的东西?如何查找Spring HandlerInterceptor在处理程序上调用的方法?

拦截器是这样的:

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 action会让缓存的响应失效,这是由一个新的widget保存的。

编辑:我已升级到最新的Spring 3.1 M2,因为this blog post暗示了我需要的功能,但目前还不清楚是否需要注入这些新类或对它们进行子类别分类。有没有人用它们在拦截器中检索HandlerMethod?

+1

好吧,我想通了这一点。然而......“声誉低于100的用户无法在8个小时内回答自己的问题” - 所以如果您处于座位边缘等待解决方案,请牢牢抓住...... –

回答

7

确定这样的解决方案实际上是很容易:

1)升级到春季3.1

2)RTFM(正常)

例如一个HandlerInterceptor接口可以从Object强制的处理程序HandlerMethod并访问目标控制器方法,其注释等

3)将句柄r拦截器中的HandlerMethod对象。

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

HandlerMethod method = (HandlerMethod) handler; 
    Cacheable methodAnnotation = method.getMethodAnnotation(Cacheable.class); 
    if (methodAnnotation != null) { 
     System.out.println("cacheable request"); 
    } 
0
@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/

相关问题