简体   繁体   English

带有注释的Spring HandlerInterceptor映射

[英]Spring HandlerInterceptor mapping with annotations

Good day. 美好的一天。 I got a spring mvc application and 2 controllers inside. 我有一个spring mvc应用程序和2个控制器。 First controller (PublicController) can process requests from all users, Second (PrivateController) can only process authorized users. 第一个控制器(PublicController)可以处理来自所有用户的请求,Second(PrivateController)只能处理授权用户。

So I implemented two Handler Interceptor`s 所以我实现了两个Handler Interceptor

@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 LoggerInterceptor to handle all controller's requests, and my AccessInterceptor to handle only PrivateController 's requests. 我需要我的LoggerInterceptor来处理所有控制器的请求,而我的AccessInterceptor只需要处理PrivateController的请求。 I must map Interceptors to Controllers with annotations 我必须使用注释将Interceptors映射到Controllers

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/**");;
    }

}

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());
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM