java 带有注释的 Spring HandlerInterceptor 映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16706806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:43:21  来源:igfitidea点击:

Spring HandlerInterceptor mapping with annotations

javaspringmodel-view-controller

提问by user2160696

Good day. I got a spring mvc application and 2 controllers inside. First controller (PublicController) can process requests from all users, Second (PrivateController) can only process authorized users.

再会。我有一个 spring mvc 应用程序和 2 个控制器。第一个控制器(PublicController)可以处理所有用户的请求,第二个(PrivateController)只能处理授权用户。

So I implemented two Handler Interceptor`s

所以我实现了两个Handler拦截器

@Configuration
@EnableWebMvc
@ComponentScan(basePackages="webapp.base.package")
public class WebApplicationConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoggerInterceptor());
        registry.addInterceptor(new AccessInterceptor());
    }

}

I need my LoggerInterceptorto handle all controller's requests, and my AccessInterceptorto handle only PrivateController's requests. I must map Interceptorsto Controllerswith annotations

我需要LoggerInterceptor处理所有控制器的请求,而我AccessInterceptor只需要处理PrivateController的请求。我必须用注释映射InterceptorsControllers

回答by user2160696

Just solve it.

就解决吧。

@Configuration
@EnableWebMvc
@ComponentScan(basePackages="webapp.base.package")
public class WebApplicationConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoggerInterceptor()).addPathPatterns("/**");;
        registry.addInterceptor(new AccessInterceptor()).addPathPatterns("/private/**");;
    }

}

回答by craig_wu9

I don't know why, when I use your way, it worked. But the interceptor executed twice. And I found another way to do this.

我不知道为什么,当我用你的方式时,它奏效了。但是拦截器执行了两次。我找到了另一种方法来做到这一点。

    @Bean
    public MappedInterceptor interceptor() {
        return new MappedInterceptor(null, new String[]{"/","/**/*.js", "/**/*.html", "/**/*.css"}, new LogInterceptor());
    }