SpringMVC中RequestContextHolder获取请求信息
chenguangming9 · 257浏览 · 发布于2020-04-03
RequestContextHolder的作用是:
在Service层获取获取request和response信息
代码示例:
ServletRequestAttributes attrs = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attrs.getRequest();
源码分析:
定义了两个ThreadLocal变量用来存储Request
private static final ThreadLocal<RequestAttributes> requestAttributesHolder = new NamedThreadLocal("Request attributes"); private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder = new NamedInheritableThreadLocal("Request context");
设置方法
public static void setRequestAttributes(@Nullable RequestAttributes attributes) { setRequestAttributes(attributes, false); } public static void setRequestAttributes(@Nullable RequestAttributes attributes, boolean inheritable) { if (attributes == null) { resetRequestAttributes(); } else if (inheritable) { inheritableRequestAttributesHolder.set(attributes); requestAttributesHolder.remove(); } else { requestAttributesHolder.set(attributes); inheritableRequestAttributesHolder.remove(); } }
是在SpringMVC处理Servlet的类FrameworkServlet的类中,doget/dopost方法,调用processRequest方法进行初始化上下文方法中initContextHolders设置进去的
private void initContextHolders(HttpServletRequest request, @Nullable LocaleContext localeContext, @Nullable RequestAttributes requestAttributes) { if (localeContext != null) { LocaleContextHolder.setLocaleContext(localeContext, this.threadContextInheritable); } if (requestAttributes != null) { RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable); } if (this.logger.isTraceEnabled()) { this.logger.trace("Bound request context to thread: " + request); } }
再看一下请求信息怎么获取
@Nullable public static RequestAttributes getRequestAttributes() { RequestAttributes attributes = (RequestAttributes)requestAttributesHolder.get(); if (attributes == null) { attributes = (RequestAttributes)inheritableRequestAttributesHolder.get(); } return attributes; }
相关推荐
PHP实现部分字符隐藏
沙雕mars · 1324浏览 · 2019-04-28 09:47:56
Java中ArrayList和LinkedList区别
kenrry1992 · 907浏览 · 2019-05-08 21:14:54
5月语言排行榜:R 跌出前二十,Python 紧咬 C++
manongba · 686浏览 · 2019-05-09 17:27:24
Tomcat 下载及安装配置
manongba · 968浏览 · 2019-05-13 21:03:56
什么是SpringBoot
iamitnan · 1086浏览 · 2019-05-14 22:20:36
分类专栏
最新发布
最热排行
0评论