zoukankan      html  css  js  c++  java
  • SpringBoot实现登陆拦截

    一、创建interceptor包,在interceptor中创建一个拦截器并实现HandlerInterceptor

    代码:

    @Component
    public class LoginHandlerInterceptor implements HandlerInterceptor {
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
           //拦截逻辑
            Object user = request.getSession().getAttribute("loginUser");
            if (user == null) {
                System.out.println("没有权限请先登陆");
                //未登陆,返回登陆界面
                request.setAttribute("msg","没有权限请先登陆");
                request.getRequestDispatcher("/login").forward(request,response);
                return false;
            } else {
                //已登陆,放行请求
                return true;
            }
        }
    }

    注意一下:在低版本的SpringBoot中需要实现postHandle方法和afterCompletion方法,高版本的SpringBoot需要用到这两个方法直接重写就行了,在这就不做过多的介绍了。

    二、创建一个SpringMvc配置类并实现WebMvcConfigurer类

    代码:

    @Configuration
    public class MyWebMvcConfiguration implements WebMvcConfigurer {
    
        @Autowired
        LoginHandlerInterceptor loginHandlerInterceptor;
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("forward:/login");
            registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        }
    
        //注册拦截器
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            //拦截所有的请求
            registry.addInterceptor(loginHandlerInterceptor).addPathPatterns("/**").excludePathPatterns("/login", "/register").excludePathPatterns("/static/**");
        }
    
    }

    注意:在SpringBoot中,只能通过创建SpringMVC配置文件来注册拦截器,

    .addPathPatterns("/**")表示拦截所有的请求,
    excludePathPatterns表示路径不需要拦截哪些路径
    一定要在这里排除拦截static路径下的静态文件,或者在SpringBoot配置文件上配置,否则页面加载不到样式
  • 相关阅读:
    android第四天晚:绘图和handle
    第二天学英语:django 第二章 get started(1)
    C#进程间的同步,实现只能运行一个程序的效果
    C# Winform Chart的配置
    C#平台调用的步骤
    分享一个开源小工具,关于单词的
    C#的log4net、log2console、rollingfile综合配置
    C#,字符串加密
    使用C#尽可能以最少的代码完成多层次的软件配置(基于PropertyGrid控件)
    C# Winform 单例的Form窗体
  • 原文地址:https://www.cnblogs.com/lzhdonald/p/logininterceptor.html
Copyright © 2011-2022 走看看