每一个请求到达服务器,Tomcat都会开启一个线程处理这个请求,从拦截器->controller->service->dao、在到数据返回到客户端都是同一个线程,那么在同一个线程之间,上一层放的数据如拦截器、或者controller,在下一层=数据需要共享,这里就可以使用ThreadLocal;

ThreadLocal-同一个线程共享数据_拦截器

ThreadLocal的核心原理就是一个Map<Thread,Object> threadLocal,将每个线程做为key,当前线程需要共享的值就是Object,使用ThreadLocal就能实现跨层数据共享;

代码实现

1.创建SpringBoot项目
2.创建拦截器

/**
* @description: 拦截器
* @author TAO
* @date 2020/8/1 22:30
*/
@Component
public class MyInterceptor implements HandlerInterceptor {

//线程共享数据对象
public static ThreadLocal<String> threadLocal = new ThreadLocal<>();

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("请求经过拦截器--准备给threadLocal中添加数据");
threadLocal.set("yyy");
return true;
}
}

3.WebMvcConfigurer添加拦截器

/**
* @description: web核心配置
* @author TAO
* @date 2020/7/30 14:34
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {

@Resource
private MyInterceptor myInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**");// /**myInterceptor要拦截所有请求
}
}

4.controller编写

@GetMapping("/getInterceptorData")
public String getInterceptorData( HttpSession session){
System.out.println("当前层--controller");
System.out.println(MyInterceptor.threadLocal.get());
return "oth1";
}

5.请求测试

ThreadLocal-同一个线程共享数据_数据_02


搞定!!!