Spring HandlerInterceptor mapping with annotations

感情迁移 提交于 2020-01-01 08:49:24

问题


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.

So I implemented two Handler Interceptor`s

@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. I must map Interceptors to Controllers with annotations


回答1:


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

}



回答2:


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


来源:https://stackoverflow.com/questions/16706806/spring-handlerinterceptor-mapping-with-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!