1.前景,有时候我们在不同的地方需要使用用户的信息,我们可以使用threadLocal存储信息,这样我们在在这个线程随时使用用户信息了,不用自己在写一段冗余代码了,这时候使用拦截器就很不错
2.实现
1.实现HandlerInterceptor
2.重写实现方法 preHandle:在业务处理器处理请求之前被调用 postHandle:在业务处理器处理请求执行完成后 afterCompletion:在完全处理完请求后被调用,可用于清理资源等
3.创建配置类,配置拦截器需要拦截的路径
案例:
/** * @Author * @Date 2024/3/10 17:45
* @desc 创建threadLocal存放数据 */ public class AuthContextHolder { private static ThreadLocal<Long> userId = new ThreadLocal<>(); //仓库id private static ThreadLocal<Long> wareId = new ThreadLocal<>(); private static ThreadLocal<UserLoginVo> userLoginVo = new ThreadLocal<>(); //后台管理用户id private static ThreadLocal<Long> adminId = new ThreadLocal<Long>(); //管理员基本信息 private static ThreadLocal<AdminLoginVo> adminLoginVo = new ThreadLocal<>(); public static Long getUserId(){ return userId.get(); } public static void setUserId(Long _userId){ userId.set(_userId); } public static Long getWareId(){ return wareId.get(); } public static void setWareId(Long _wareId){ wareId.set(_wareId); } public static UserLoginVo getUserLoginVo() { return userLoginVo.get(); } public static void setUserLoginVo(UserLoginVo _userLoginVo) { userLoginVo.set(_userLoginVo); } public static Long getAdminId() { return adminId.get(); } public static void setAdminId(Long _adminId) { adminId.set(_adminId); } public static AdminLoginVo getAdminLoginVo() { return adminLoginVo.get(); } public static void setAdminLoginVo(AdminLoginVo _adminLoginVo) { adminLoginVo.set(_adminLoginVo); } }
创建拦截器,通过重写preHandle方法在调用方法前将数据放到线程中
public class LoginInterceptor implements HandlerInterceptor { private RedisTemplate redisTemplate; LoginInterceptor(RedisTemplate redisTemplate){ this.redisTemplate = redisTemplate; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token = request.getHeader("token"); if (StringUtils.isEmpty(token)) { Long userId = JwtHelper.getUserId(token); UserLoginVo userLoginVo = (UserLoginVo) redisTemplate.opsForValue().get(RedisConst.USER_LOGIN_KEY_PREFIX + userId); if (userLoginVo != null) { AuthContextHolder.setUserId(userId); AuthContextHolder.setUserLoginVo(userLoginVo); AuthContextHolder.setWareId(userLoginVo.getWareId()); } } return true; } }
具体拦截方法,可按需求拦截
addPathPatterns需要拦截的方法。
excludePathPatterns排除在外的方法
public class LoginMvcConfigurerAdapter extends WebMvcConfigurationSupport { @Resource private RedisTemplate redisTemplate; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginInterceptor(redisTemplate)) .addPathPatterns("/api/**") .excludePathPatterns("/api/user/weixin/wxLogin/*"); super.addInterceptors(registry); } }
这样我们就可以在方法中随时通过调用threaLocal获取存在里面的用户信息
标签:拦截器,java,springboot,userLoginVo,userId,ThreadLocal,static,public,redisTemplate From: https://www.cnblogs.com/gsyy/p/18064540