【问题标题】:How can I lookup the method being called on a Handler from a Spring HandlerInterceptor?如何从 Spring HandlerInterceptor 查找在 Handler 上调用的方法?
【发布时间】:2011-11-09 13:31:54
【问题描述】:

我有一个 Spring HandlerInterceptor 拦截我的应用程序 (/app/*) 中的前端 URL。我想确定将要从 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,this blog post 暗示了我需要的功能,但不清楚是否需要注入这些新类或对它们进行子类化。有人用它们在拦截器中检索 HandlerMethod 吗?

【问题讨论】:

  • 好的,我想通了。但是...“声誉低于 100 的用户无法在 8 小时内回答他们自己的问题”-因此,如果您在座位边缘等待解决方案,请坚持住...

标签: java spring spring-mvc


【解决方案1】:

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

1) 升级到 Spring 3.1

2) RTFM(正确)

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

3) 将处理程序对象强制转换为拦截器中的 HandlerMethod。

那么你可以做这样的事情:

    HandlerMethod method = (HandlerMethod) handler;
    Cacheable methodAnnotation = method.getMethodAnnotation(Cacheable.class);
    if (methodAnnotation != null) {
        System.out.println("cacheable request");
    }

【讨论】:

    【解决方案2】:
    @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/有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2015-10-09
      • 2015-01-30
      • 1970-01-01
      • 2012-12-24
      相关资源
      最近更新 更多