Spring Boot2.0拦截器简单实现判断是否登录

在进行项目开发的时候使用springboot框架用到拦截器时发现2.0以后原来的抽象类WebMvcConfigurerAdapter已经过时了,去官网查文档2.x版本要实现拦截器功能改为需要继承WebMvcConfigurer接口。
Spring Boot2.0拦截器简单实现判断是否登录
实现拦截器大致分为两步

创建我们自己的拦截器类并实现 HandlerInterceptor 接口

//创建拦截器BackInterceptor并实现接口HandlerInterceptor
public class BackInterceptor implements HandlerInterceptor {
    //重写preHandle方法
    @Override
    public boolean preHandle(  HttpServletRequest request, HttpServletResponse response,Object handler)   throws Exception {
   		 //判断session里是否有user
       if (null == request.getSession().getAttribute("user")) {
			return false;
       }
          return true;
    }
}

其实重写WebMvcConfigurerAdapter中的addInterceptors方法把自定义的拦截器类添加进来即可


//创建一个实现WebMvcConfigurer接口的类
public class MyWebMvcConfigurerAdapter implements WebMvcConfigurer {
    //获取拦截器的Bean
    @Bean
    public HandlerInterceptor getBackInterceptor() {
        return new BackInterceptor();
    }

    /**
     * 重写addInterceptors方法
     * addPathPatterns:需要拦截的访问路径
     * excludePathPatterns:不需要拦截的路径,
     * String数组类型可以写多个用","分割
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getBackInterceptor()).addPathPatterns("/admin/**").excludePathPatterns("/toLogin", "/admin/login");
    }
}

拦截器测试,拦截了addPathPatterns("/admin/**")也就是admin下的所有资源
Spring Boot2.0拦截器简单实现判断是否登录
可以看到访问路径http://localhost:10010/admin后显示的是错误页面

下面试一下访问不需要拦截的路径excludePathPatterns("/toLogin")
http://localhost:10010/toLogin
Spring Boot2.0拦截器简单实现判断是否登录
成功访问到登录页面

欢迎关注微信公众号:看到我请叫我滚去学习