美文网首页
SpringBoot自定义拦截器

SpringBoot自定义拦截器

作者: Laity_9c91 | 来源:发表于2021-10-25 13:52 被阅读0次

    1. 新建一个类实现HandlerInterceptor接口,覆盖接口中的方法

    public class LoginInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //获取session对象
            HttpSession session = request.getSession();
            //获取存到session中的值,session有值就放行,否则不放行
            User user = (User) session.getAttribute(UserInfoEnum.USER_NAME.getUserSessionInfo());
            if (user==null){
                //重定向
                response.sendRedirect("/api/login");
                return false;
            }
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    
        }
    }
    

    2. 写一个配置类,实现WebMvcConfigurer接口。覆盖其中的addInterceptors方法,编写拦截逻辑

    package com.littlenorth.config;
    
    
    import com.littlenorth.handler.LoginInterceptor;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    /**
     * @author lovelittlenorth
     * @create 2021/10/24 23:26
     */
    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
    
        //注入自定义登录拦截器
        @Bean
        public LoginInterceptor loginInterceptor(){
            return new LoginInterceptor();
        }
    
    
        /**
         * 注册拦截器
         * @param registry
         */
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            //注册拦截器,拦截那些请求,放行那些请求
           registry.addInterceptor(loginInterceptor()).addPathPatterns("/api/**").excludePathPatterns("/api/login","/static/**");
        }
    }
    

    打完收工

    相关文章

      网友评论

          本文标题:SpringBoot自定义拦截器

          本文链接:https://www.haomeiwen.com/subject/qfwjaltx.html