SpringBoot(五):SpringBoot使用拦截器

1.按照SpringMVC的方式编写一个拦截器:

2.配置一个类   implements WebMvcConfigurer 接口 为该类添加注解@Configuration  (等价于一个spring的xml文件 比如applicationContext.xml) 标注一个配置类,让Springboot扫描到。覆盖其中的方法并添加已经编写好的拦截器

贴段代码:

@Configuration   // 等价于一个spring的xml文件 比如applicationContext.xml
public class WebConfig implements WebMvcConfigurer {
    /**
     * 添加拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 拦截器要拦截的路径
        String [] pathPatterns = {
                "/**"
        };
        // 拦截器不拦截的路径
        String [] excluedPathPatterns = {
                "/boot/hello",
                "boot/jsp"
        };
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns(pathPatterns).excludePathPatterns(excluedPathPatterns);

        //如果项目中有多个拦截器,把上面代码在复制一行,修改参数即可

    }
}

  

addPathPatterns(pathPatterns)和excludePathPatterns(excluedPathPatterns)是可变参数,二u过要拦截的路径只有一条,可以直接写路径名字,不用写数组,如
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/boot/**").excludePathPatterns(/boot/login);

  

猜你喜欢

转载自www.cnblogs.com/shenlailai/p/10464197.html