打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
SpringMVC中RequestContextHolder获取请求信息

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;    }
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
[Java] SpringMVC工作原理之一:DispatcherServlet
利用电脑玩Android版“天天连萌”刷高分(四)
跟开涛学SpringMvc
java接口防重提交如何处理
合集·SpringMVC详解(1/14)
SpringMVC3.1 Hibernate4.1.7完全基于注解配置(零配置文件)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服