Skip to content

Latest commit

 

History

History

213-web-interceptor

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

213-web-interceptor

项目说明

Spring MVC 拦截器,注意它不属于Servlet的三件套,而是Spring生态中的一个环,在具体的web handler执行之前,可用于拦截某些请求

从最终的使用效果来说,它和filter貌似也没有太多的差别;但是在业务处理流程中它是在servlet内部执行的;而filter是在servlet执行之前过滤

重点注意一下,拦截器的注册方式,实现 WebMvcConfigure接口,覆盖addInterrceptors方法来注册

@SpringBootApplication
public class Application implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/**");
    }
}

若我们希望将拦截器声明为bean对象,可以如下操作

@SpringBootApplication
public class Application implements WebMvcConfigurer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }

    @Bean
    public SecurityInterceptor securityInterceptor() {
        return new SecurityInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(securityInterceptor()).addPathPatterns("/**");
    }
}

相关博文: