springboot 錯誤記錄

1.攔截器中handler cannot be cast to HandlerMethodjava

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,就會拋出上述錯誤。web

解決辦法:spring

1.攔截器那裏排除靜態資源的請求路徑spa

registry.addInterceptor(new MyInterceptor()).addPathPatterns("/xx/**")
                .excludePathPatterns("/xx/**");

2. instanceof關鍵字進行判斷。code

if(handler instanceof ResourceHttpRequestHandler) {
                logger.info("---------ResourceHttpRequestHandler-------" + handler.toString() + "------------");
            }else if(handler instanceof HandlerMethod){
                logger.info("--------HandlerMethod--------" + handler.toString() + "------------");
            }
相關文章
相關標籤/搜索