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配置文件上配置,否则页面加载不到样式
  • 相关阅读:
    .net 文件夹是否存在的判断
    Lock Statement And Thread Synchronization
    如何利用EnteLib Unity Interception Extension 和PIAB实现Transaction
    OSQL 命令行工具
    How to build tab sets whitch headers display at bottom in WPF?
    Monitoring Clipboard Activity in C#
    产品经理讲座的感悟
    图说
    解决技术问题的9点建议
    为啥要整理需求?
  • 原文地址:https://www.cnblogs.com/lzhdonald/p/logininterceptor.html
Copyright © 2011-2022 走看看