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配置文件上配置,否则页面加载不到样式
  • 相关阅读:
    单片机GPIO口模拟串口的方法
    arduino~snprintf
    #7号板问题
    stm8s + si4463 寄存器配置
    linux之cut用法
    74HC123D 引脚介绍及应用
    无线板卡接口定义
    iio adc转换应用编写
    m72 gprs模块的应用编写
    dac7562 应用层实现dac
  • 原文地址:https://www.cnblogs.com/lzhdonald/p/logininterceptor.html
Copyright © 2011-2022 走看看