SpringBoot添加拦截器

SpringBoot添加拦截器

项目结构

在这里插入图片描述

配置文件

  1. application.yaml

    server:
      port: 8089
    
    spring:
      application:
        name: cart-service
      redis:
        host: 192.168.79.128
    
    eureka:
      client:
        service-url:
          defaultZone: http://127.0.0.1:10086/eureka
        registry-fetch-interval-seconds: 10 # 每10秒拉一次注册信息
      instance:
        prefer-ip-address: true
        ip-address: 127.0.0.1
    
    
    ly:
      jwt:
        pubKeyPath: E:\\leyoushop\\rsa\\rsa.pub # 公钥地址
        cookieName: LY_TOKEN # cookie的名称
    

启动类

  1. LyCartApplication

    package com.leyou;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    
    /**
     * @program: leyou
     * @description:
     * @author: Mr.Xiao
     * @create: 2020-07-08 15:12
     **/
    @SpringBootApplication
    @EnableDiscoveryClient
    public class LyCartApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(LyCartApplication.class);
        }
    
    }
    

config

  1. JwtProperties

    package com.leyou.cart.config;
    
    import com.leyou.auth.utils.RsaUtils;
    import lombok.Data;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    
    import javax.annotation.PostConstruct;
    import java.security.PublicKey;
    
    /**
     * @program: leyou
     * @description:
     * @author: Mr.Xiao
     * @create: 2020-07-06 13:52
     **/
    @Data
    @ConfigurationProperties(prefix = "ly.jwt")
    public class JwtProperties {
    
        private String pubKeyPath;
        private String cookieName;
    
        private PublicKey pubKey;
    
        @PostConstruct
        public void init() throws Exception {
            this.pubKey = RsaUtils.getPublicKey(pubKeyPath);
        }
    
    }
    
  2. UserConfig—(注册拦截器)

    package com.leyou.cart.config;
    
    import com.leyou.cart.Interceptor.UserInterceptor;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    @EnableConfigurationProperties(JwtProperties.class)
    public class UserConfig implements WebMvcConfigurer {
    
        @Autowired
        private JwtProperties prop;
    
        /**
         * 添加拦截器  (把自定义的拦截器---注册进去)
         * @param registry
         */
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            /*
                需要拦截的路径,通常都是多个,所以使用数组形式
                String[] addPathPatterns = {
                    "/cart/update"
                };
             */
    
            /*
                不需要的拦截路径,同上
                String[] excludePathPatterns = {
                    "/cart/list"
                };
             */
    
            /*
                可以将添加拦截的路径和不需要拦截的路径都写在一行上。如果有多个,就写多行
                registry.addInterceptor(new MyInterceptor()).addPathPatterns(addPathPatterns).excludePathPatterns(excludePathPatterns);
             */
    
            /*
                 /**: 拦截一起路径
                 registry.addInterceptor: 添加拦截器
                 addPathPatterns: 添加拦截的路径
                 优于我这里是new出来的对象, 不是spring自动注册的, 所以UserInterceptor里面的EnableConfigurationProperties不能用
             */
            registry.addInterceptor(new UserInterceptor(prop)).addPathPatterns("/**");
            /*
            设置拦截器顺序, 通过配置order()的值,值越小,优先级越高。不配默认是0
            registry.addInterceptor(new UserInterceptor(prop)).addPathPatterns("/**").order(100);
           */
        }
    }
    

interceptor

  1. UserInterceptor—(自定义拦截器)

    package com.leyou.cart.Interceptor;
    
    import com.leyou.auth.pojo.UserInfo;
    import com.leyou.auth.utils.JwtUtils;
    import com.leyou.cart.config.JwtProperties;
    import com.leyou.common.utils.CookieUtils;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.web.servlet.HandlerInterceptor;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @program: leyou
     * @description: 自定义拦截器
     * @author: Mr.Xiao
     * @create: 2020-07-08 10:02
     **/
    @Slf4j
    public class UserInterceptor implements HandlerInterceptor {
    
        private JwtProperties prop;
    
        // 线程的名称就是key, 你存的值就是该key的值
        private static final ThreadLocal<UserInfo> threadLocal = new ThreadLocal<>();
    
        public UserInterceptor(JwtProperties prop) {
            this.prop = prop;
        }
    
        /**
         * 预处理, 在controller执行之前 返回true放行, 返回false拦截
         * @param request
         * @param response
         * @param handler
         * @return
         * @throws Exception
         */
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
            try{
                // 获取cookie里的token
                String token = CookieUtils.getCookieValue(request, prop.getCookieName());
                // 解析token, 获取用户信息
                UserInfo user = JwtUtils.getInfoFromToken(token, prop.getPubKey());
    
                // 将用户信息, 保存进线程容器中
                threadLocal.set(user);
    
                // 放行
                return true;
            } catch (Exception e) {
                log.error("[购物车服务]---解析身份失败: ", e);
                return false;
            }
    
        }
    
        /**
         * 视图执行完成以后, 删除该键值对
         * @param request
         * @param response
         * @param handler
         * @param ex
         * @throws Exception
         */
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            threadLocal.remove();
        }
    
        /**
         * 获取用户信息
         * @return
         */
        public static UserInfo getUser() {
            return threadLocal.get();
        }
    
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

只因为你温柔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值