RequestContextHolder

一、概述

RequestContextHolder顾名思义,持有上下文的Request容器。

子线程无法获取 requestAttributes
参考:https://blog.csdn.net/qq_25775675/article/details/125617310

二、案例

从中我们可以获取到requestresponsesession等对象。

//两个方法在没有使用JSF的项目中是没有区别的
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
//RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

//从session里面获取对应的值
String name = (String) requestAttributes.getAttribute("name", RequestAttributes.SCOPE_SESSION);

//类型转换
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)requestAttributes;

//获取到Request对象
HttpServletRequest request = servletRequestAttributes.getRequest();
//获取到Response对象
HttpServletResponse response = servletRequestAttributes.getResponse();
//获取到Session对象
HttpSession session = request.getSession();

三、实现原理

1、存储变量

首先分析RequestContextHolder这个类,里面有两个ThreadLocal保存当前线程下的request

//得到存储进去的request
private static final ThreadLocal<RequestAttributes> requestAttributesHolder 
    = new NamedThreadLocal<RequestAttributes>("Request attributes");
//可被子线程继承的request
private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder 
    = new NamedInheritableThreadLocal<RequestAttributes>("Request context");

2、获取

/*返回当前绑定到线程的RequestAttributes@返回当前绑定到线程的RequestAttributes,如果未绑定,则返回{@code null}*/
@Nullable
public static RequestAttributes getRequestAttributes() {
    RequestAttributes attributes = requestAttributesHolder.get();
    if (attributes == null) {
        attributes = inheritableRequestAttributesHolder.get();
    }
    return attributes;
}

3、存入

request和response等是什么时候设置进去的?

参考:

SpringMVC之RequestContextHolder分析
https://blog.csdn.net/Hu199055/article/details/79135778
https://www.cnblogs.com/shuilangyizu/p/8621669.html

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值