我的项目在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
异常的原因是什么?
最佳答案
这仅表示handler
不是HandlerMethod
的实例,因此强制转换失败。进行投放前检查,如下所示:
if (handler instanceof HandlerMethod) {
HandlerMethod maControl = (HandlerMethod) handler;
Method pmrResolver = (Method) maControl.getMethod();
String methodName = pmrResolver.getName();
// ...
}