一、概述
RequestContextHolder
顾名思义,持有上下文的Request容器。
子线程无法获取 requestAttributes
参考:https://blog.csdn.net/qq_25775675/article/details/125617310
二、案例
从中我们可以获取到request
、response
、session
等对象。
//两个方法在没有使用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