SpringMVC中RequestContextHolder获取请求信息

RequestContextHolder的作用是:

​ 在Service层获取获取request和response信息

代码示例:

ServletRequestAttributes attrs = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attrs.getRequest();
源码分析:

定义了两个ThreadLocal变量用来存储Request

private static final ThreadLocal requestAttributesHolder = new NamedThreadLocal(“Request attributes”);
private static final ThreadLocal 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;
}
 亚马逊测评 www.yisuping.com
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值