Spring mvc拦截器异常

时间:2013-08-28 06:54:58

标签: java spring-mvc interceptor

我的项目是在spring mvc上加载的,我编写了一个截取拦截请求的拦截器,我想从请求获取参数,以下是我的代码:

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    HandlerMethod maControl = (HandlerMethod) handler;  
    Method pmrResolver = (Method) maControl.getMethod();  
    String methodName = pmrResolver.getName(); 
        ....
}

但现在它引发了一个异常:

java.lang.ClassCastException: org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler cannot be cast to  org.springframework.web.method.HandlerMethod

异常的原因是什么?

1 个答案:

答案 0 :(得分:2)

它只是意味着handler不是HandlerMethod的实例,因此强制转换失败。在铸造之前检查如下:

if (handler instanceof HandlerMethod) {
    HandlerMethod maControl = (HandlerMethod) handler;  
    Method pmrResolver = (Method) maControl.getMethod();  
    String methodName = pmrResolver.getName(); 
    // ...
}