• SpringBoot2.0拦截器 与 1.X版本拦截器 的实现


    1.5  版本 

    先写个拦截器,跟xml配置方式一样,然后将拦截器加入spring容器管理 。接着创建 配置文件类 继承 WebMvcConfigurerAdapter 类,重写父类方法addInterceptors

        

    @Component
    public class MyInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
           //true放行  false拦截
            System.out.println("拦截");
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
            System.out.println("preHandle()执行过后再执行");
            System.out.println("controller执行前再执行");
        }
    
        @Override
        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
            System.out.println("controller执行过后再执行");
        }
    }
    拦截器类
    @Configuration
    public class WebConfig extends WebMvcConfigurerAdapter{
    
        @Autowired
        private MyInterceptor myInterceptor;
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(myInterceptor)
                    .addPathPatterns("/**")
                    .excludePathPatterns("/index","/login");
            super.addInterceptors(registry);
        }
    
    }
    配置文件类

    2.0  版本跟1.5一样 就是配置类需要的是实现WebMvcConfigurer接口不再是继承 WebMvcConfigurerAdapter 类 ,通过spring代码可以发现   WebMvcConfigurerAdapter implements WebMvcConfigurer 这种关系.

    @Configuration
    public class MvcConfig  implements WebMvcConfigurer {
        @Autowired
        private MyInterceptor myInterceptor;
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(webInterceptor())
                    .addPathPatterns("/**")
                    .excludePathPatterns("/asserts/**","/receiveToken","/ssoLogout","/ssoDeleteToken");
            ;
        }
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //addResourceLocations指的是文件放置的目录,addResoureHandler指的是对外暴露的访问路径
            registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        }
    
    }
    配置文件类

      

  • 相关阅读:
    翻转数组
    C语言之指针
    C语言之结构体
    C语言之函数
    数据结构之typedef
    数据结构之树
    数据结构之链表
    数据结构之队列
    数据结构之数组
    ssh远程连接控制 linux 口令、密钥连接
  • 原文地址:https://www.cnblogs.com/wenbuzhu/p/9967737.html
Copyright © 2020-2023  润新知