zoukankan      html  css  js  c++  java
  • SpringMVC中RequestContextHolder获取请求信息

    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;
        }
    
  • 相关阅读:
    Linux进程组调度机制分析【转】
    Linux内存管理 (22)内存检测技术(slub_debug/kmemleak/kasan)【转】
    linux syscall 详解【转】
    Linux C 读取文件夹下所有文件(包括子文件夹)的文件名【转】
    Linux RTC驱动模型分析之rtc-sysfs.c【转】
    Linux的notifier机制在TP中的应用【转】
    Linux内存管理 (10)缺页中断处理【转】
    proc/net/dev实时网速统计实例【转】
    硬中断和软中断【转】
    Linux网络
  • 原文地址:https://www.cnblogs.com/undefined22/p/12624699.html
Copyright © 2011-2022 走看看