threadLocal的运用

复制代码
 RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //使用哪一个取决于springmvc在保存request信息时具体用的子类,他们通常无父子单独实现、
        //如果有父子可以继承第一个持有的httpServletRequest
        HttpServletRequest request = ((ServletWebRequest) requestAttributes).getRequest();
        //ServletRequestAttributes它是spring的具体保存的实例实现,通过名字和实现目的 接口是属性目的获取请求servlet
//        ServletRequestAttributes它是最上乘的类其他实现者以继承它保存的request并初始出自己的,并提供自己的get和set
         HttpServletRequest request1 = ((ServletRequestAttributes) requestAttributes).getRequest();
        HttpServletRequest request3 = ((StandardServletAsyncWebRequest) requestAttributes).getRequest();

        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        System.out.println(requestURI+method);

抽象类 RequestContextHolder提供静态方法,获取全局的threadlocal对象,对象中存一个请求属性对象接口,该接口有多个实现类,提供顶层接口以外的附加功能,但在springMVC中把请求保存在当前线程的只会有一个实例实现,其他实例通过继承这个实例同样持有到属性接口实例持有的HttpServletRequest对象,通过 RequestContextHolder类为每一个请求到的线程中都加上一个缓存map,值的接口实例持有请求属性,由于是静态的属性所以所有线程可以使用设置自己的值,获取线程之间存值有交集

复制代码
 private static final ThreadLocal<RequestAttributes> requestAttributesHolder = new NamedThreadLocal("Request attributes");
    private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder = new NamedInheritableThreadLocal("Request context");
相关推荐
百花~34 分钟前
Spring Web MVC~
前端·spring·mvc
a***97681 小时前
使用 Logback 的最佳实践:`logback.xml` 与 `logback-spring.xml` 的区别与用法
xml·spring·logback
rit84324991 小时前
配置Spring框架以连接SQL Server数据库
java·数据库·spring
q***615010 小时前
eclipse配置Spring
java·spring·eclipse
q***581910 小时前
Spring全家桶简介
java·后端·spring
凌波粒10 小时前
SpringMVC基础教程(4)--Ajax/拦截器/文件上传和下载
java·前端·spring·ajax
戮戮11 小时前
从 Spring @Retryable 到 Kafka 原生重试:消息重试方案的演进与最佳实践
spring·kafka·linq
麦兜*11 小时前
Redis内存消耗异常飙升?深入排查与Big Key/Hot Key的根治方案
jvm·数据库·spring boot·redis·spring·缓存
小七mod12 小时前
【Spring】Spring Boot自动配置的案例
java·spring boot·spring·自动配置·源码·ioc·aop
java干货12 小时前
Spring Boot 为什么“抛弃”了 spring.factories?
spring boot·python·spring