【问题标题】:Spring Boot 2.0 Intercepting the HandlerMethod of a RequestSpring Boot 2.0 拦截请求的HandlerMethod
【发布时间】:2018-11-24 17:33:58
【问题描述】:

我正在从 Spring Boot 1.x 升级到 Spring Boot 2.0,并注意到我的 HandlerInterceptors 中开始出现类转换错误。

例如,在一个HandlerInterceptor 中,我查看控制器方法/端点是否用@AdminOnly 注释以限制对某些端点的访问。

@Component
public class AdminOnlyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Object handler) {
        HandlerMethod hm = (HandlerMethod) handler;
        Method method = hm.getMethod();
        if (method.getDeclaringClass().isAnnotationPresent(RestController.class) && (method.isAnnotationPresent(AdminOnly.class) || method.getDeclaringClass().isAnnotationPresent(AdminOnly.class))) {
            // Some Logic returning true or false
        }
        return true;
    }
}

这在 Spring Boot 1.5.x 中有效。

升级后我现在得到以下异常:

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

我在migration guide 中找不到任何相关内容。如何升级但保持上面的拦截器正常工作?

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    看来 Spring Boot 2.x 拦截器现在也处理静态资源请求,因此现在需要在注册拦截器时手动排除这些请求,如下所示:

    @Configuration
    public class ControllerConfiguration implements WebMvcConfigurer {
    
        private final AdminOnlyInterceptor adminInterceptor;
    
        @Autowired
        public ControllerConfiguration(AdminInterceptor adminInterceptor) {
            this.adminInterceptor = adminInterceptor;
        }
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(adminInterceptor)
                    .addPathPatterns("/rest-api-root/**"); // White list paths
                    //.excludePathPatterns("/static-resource-root/**"); // Black list paths
        }
    }
    

    【讨论】:

    • 我的css和js文件存在于resource/public下!我怎样才能排除它?
    • 我想你可以使用excludePathPatterns("public/**")
    • 谢谢你!你救了我的天!!我通过添加/common/**,/js/**,/css/** 得到了解决方案:)
    • 默认在 Spring boot 中。应该排除的路径是什么?
    猜你喜欢
    • 2018-07-11
    • 2019-01-14
    • 2018-08-09
    • 2013-03-17
    • 2019-02-04
    • 2021-05-06
    • 2020-11-19
    • 2019-11-17
    • 1970-01-01
    相关资源
    最近更新 更多