SpringBoot添加拦截器
项目结构
配置文件
-
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的名称
启动类
-
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
-
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); } }
-
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
-
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(); } }