1.攔截器中handler cannot be cast to HandlerMethod
java.lang.ClassCastException: org.springframework.web.servlet.resource.ResourceHttpRequestHandler cannot be cast to org.springframework.web.method.HandlerMethod
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception { //此處報錯 HandlerMethod handlerMethod = (HandlerMethod) handler; }
原因就在於,spring boot 2.0對靜態資源也進行了攔截,當攔截器攔截到請求之后,但controller里並沒有對應的請求時,該請求會被當成是對靜態資源的請求。此時的handler就是 ResourceHttpRequestHandler,就會拋出上述錯誤。
解決辦法:
1.攔截器那里排除靜態資源的請求路徑
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/xx/**") .excludePathPatterns("/xx/**");
2. instanceof關鍵字進行判斷。
if(handler instanceof ResourceHttpRequestHandler) { logger.info("---------ResourceHttpRequestHandler-------" + handler.toString() + "------------"); }else if(handler instanceof HandlerMethod){ logger.info("--------HandlerMethod--------" + handler.toString() + "------------"); }