Java教程

SpringBoot java.lang.ClassCastException:ResourceHttpRequestHandler cannot be cast to HandlerMethod

本文主要是介绍SpringBoot java.lang.ClassCastException:ResourceHttpRequestHandler cannot be cast to HandlerMethod,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Springboot 在配置个性化的webMVC时,静态资源的请求也被拦截的时候,会出现以上错误,所以需要忽略对静态资源的拦截

1) @Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    // 拦截所有请求
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(new AuthenticationInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/index.html","/","/user/login","/css/*","/js/*","/images/*","/swagger-ui.html","/**/*.html","/**/*.css","/**/*.js");
    }
}

以上代码,
excludePathPatterns  "/**/*.html","/**/*.css","/**/*.js"部分就是忽略静态资源请求的配置

2) 并在HandlerInterceptor的实现类里面判断如果时静态资源类的请求的话,直接放过通行
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       String token = request.getHeader("token");
       if((handler instanceof HandlerMethod)){// 如果不是method,直接放行
           return true;
       }
       if(handler instanceof ResourceHttpRequestHandler){
           return true;
       }
}
这篇关于SpringBoot java.lang.ClassCastException:ResourceHttpRequestHandler cannot be cast to HandlerMethod的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!