zoukankan      html  css  js  c++  java
  • springBoot 登录拦截器

    1、首选创建一个继承HandlerInterceptor的拦截器

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    /**
     * 拦截器
     */
    public class MyInterceptor implements HandlerInterceptor{
        //在请求处理之前进行调用(Controller方法调用之前
        @Override
        public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
            HttpSession session = httpServletRequest.getSession();
            String user = (String) session.getAttribute("user"); //获取登录的session信息
            if(user!=null){
                return true;
            }
            else{
    httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login/index");  //未登录自动跳转界面
                return false;
            }
        }
    
        //请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
        @Override
        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    
            System.out.println("postHandle被调用
    ");
        }
    
        //在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
        @Override
        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
            System.out.println("afterCompletion被调用
    ");
        }
    }
    

      2、继承WebMvcConfigureAdapter类,覆盖其addInterceptors接口,注册自定义的拦截器:

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
    
        /**
         * 注册拦截器
         */
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
        //addPathPattern后跟拦截地址,excludePathPatterns后跟排除拦截地址
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/login/index").excludePathPatterns("/login/login"); 
        } 
    }
    

      

    这样我们就可以在用户请求到达controller层实现登录拦截了,所有用户请求都会被拦截,在prehandle方法进行登录判断,返回true则验证通过,否则失败

  • 相关阅读:
    localStorage
    node开发 npm install -g express-generator@4
    Vue 爬坑之路(一)—— 使用 vue-cli 搭建项目
    WebSocket 教程
    解决Git报错:error: You have not concluded your merge (MERGE_HEAD exists).
    ThinkPHP5 支付宝 电脑与手机支付扩展库
    apache中通过mod_rewrite实现伪静态页面的方法
    一个PHP文件搞定微信H5支付
    Windows下安装Redis及php的redis拓展教程
    GIT 常用命令
  • 原文地址:https://www.cnblogs.com/cyrfr/p/9132986.html
Copyright © 2011-2022 走看看