当前位置:网站首页>ThreadLocal保存用户登录信息
ThreadLocal保存用户登录信息
2022-08-01 14:05:00 【独酌先生QAQ】
目录结构:

1.编写注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Target 用于描述注解的使用范围 ElementType.METHOD 用于描述方法 ElementType.TYPE 用于描述类、接口(包括注解类型) 或enum声明
* @Retention 定义被它所注解的注解保留多久
* source:注解只保留在源文件,当Java文件编译成class文件的时候,注解被遗弃;被编译器忽略
* class:注解被保留到class文件,但jvm加载class文件时候被遗弃,这是默认的生命周期
* runtime:注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExposeUserInfo {
}2.编写类user,ThreadLocal存放user类
import lombok.Data;
@Data
public class User {
String id;
String name;
}
public class UserContext {
private static ThreadLocal<User> threadLocal = new ThreadLocal<>();
public static void set(User user) {
threadLocal.set(user);
}
public static User get() {
return threadLocal.get();
}
public static void remove(){
threadLocal.remove();
}
}3.编写切面
import com.example.aopannotation.threadlocal.User;
import com.example.aopannotation.threadlocal.UserContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Aspect
@Component
public class UserInfoAspect {
public Logger logger = LoggerFactory.getLogger(UserInfoAspect.class);
/**
* 切点放在注解上,通过注解实现aop切面
*/
@Pointcut("@annotation(com.example.aopannotation.annotation.ExposeUserInfo)")
public void pointcut() {
}
@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
User user = new User();
//1.从请求头获取用户的信息
HttpServletRequest request = null;
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
request = requestAttributes.getRequest();
// 2.获取用户的id
String id = request.getHeader("id");
//此处可以查库,得到user对象的其他信息
user.setId(id);
UserContext.set(user);
try {
// 3.设置用户上下文
UserContext.set(user);
// 执行并返回
return joinPoint.proceed();
} catch (Throwable throwable) {
throw throwable;
} finally {
// 4.移除(防止内存泄漏)
UserContext.remove();
}
}
}4.编写controller
import com.example.aopannotation.annotation.ExposeUserInfo;
import com.example.aopannotation.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class ExposeController {
@Autowired
UserInfoService userInfoService;
@ExposeUserInfo
@PostMapping("/userinfo")
public String test() {
return userInfoService.getUserInfo();
}
}5.编写service
import com.example.aopannotation.threadlocal.User;
import com.example.aopannotation.threadlocal.UserContext;
import org.springframework.stereotype.Service;
@Service
public class UserInfoService {
public String getUserInfo(){
User user= UserContext.get();
return user.getId();
}
}
6.postman请求

边栏推荐
- 什么是元编程
- 模型运营是做什么的(概念模型数据库)
- iframe tag attribute description detailed [easy to understand]
- 制售假劣农资、非法占用耕地……公安部公布十起危害粮食生产安全犯罪典型案例
- 「计算复杂性」理论奠基人Juris Hartmanis逝世,曾获93年图灵奖
- Batch replace tables in Word with pictures and save
- 关于Request复用的那点破事儿。研究明白了,给你汇报一下。
- datetime64[ns] converted to datetime
- AtCoder Beginner Contest 261 D - Flipping and Bonus
- PAT1166 Summit(25)
猜你喜欢

34、树莓派进行人体姿态检测并进行语音播报

PAT 1163 Dijkstra Sequence(30)

又拿三个大奖?!多力就是要让你吃的更营养更健康

微信UI在线聊天源码 聊天系统PHP采用 PHP 编写的聊天软件,简直就是一个完整的迷你版微信

Gradle series - Gradle tests, Gradle life cycle, settings.gradle description, Gradle tasks (based on Groovy documentation 4.0.4) day2-3

龙口联合化学通过注册:年营收5.5亿 李秀梅控制92.5%股权

PAT1165 Block Reversing(25)

易优压双驱挖掘机压路机器类网站源码 v1.5.8

考研大事件!这6件事考研人必须知道!

The role of the final keyword final and basic types, reference types
随机推荐
「计算复杂性」理论奠基人Juris Hartmanis逝世,曾获93年图灵奖
2022-07-29 网工进阶(二十二)BGP-其他特性(路由过滤、团体属性、认证、AS欺骗、对等体组、子路由器、路由最大接收数量)
Istio投入生产的障碍以及如何解决这些问题
2022图片在线加水印源码
sql is not null 优化(oracle语句索引优化)
8. How does the SAP ABAP OData service support the Create operation
HTB-Shocker
MBI5020 LED驱动
性能优化——粒子优化笔记
PAT1166 Summit(25)
OpenSSL SSL_read: Connection was reset, errno 10054
Qt实战案例(55)——利用QDir删除选定文件目录下的空文件夹
灵魂发问:MySQL是如何解决幻读的?
Pytorch —— 分布式模型训练
What Can Service Mesh Learn from SDN?
How does the SAP ABAP OData service support the Create operation trial version
使用ffmpeg来查看视频的信息,fps,和width,height
如何降低Istio服务网格中Envoy的内存开销
直播系统聊天技术(八):vivo直播系统中IM消息模块的架构实践
Gradle系列——Gradle测试,Gradle生命周期,settings.gradle说明,Gradle任务(基于Groovy文档4.0.4)day2-3