RequestContextHolder详解

一、概述

RequestContextHolder是Spring框架中作为HTTP请求上下文绑定的持有者,可以方便地随时获取当前请求的HttpServletRequest、HttpServletResponse等信息,这对于Web开发来说是不可或缺的。

在Web应用程序中,一个请求可能会经过多个线程,每个线程都会处理请求的某一个环节。RequestContextHolder可以确保在整个请求处理过程中,我们都能够访问到该请求的相关信息。

二、RequestContextHolder分类

Spring框架提供了两种不同类型的RequestContextHolder:

1、RequestContextHolder使用ThreadLocal保存请求信息

public class RequestContextHolder {
 
    private static final ThreadLocal requestAttributesHolder =
            new NamedThreadLocal("Request attributes");
 
    public static void resetRequestAttributes() {
        requestAttributesHolder.remove();
    }
 
    public static void setRequestAttributes(RequestAttributes attributes) {
        Assert.notNull(attributes, "Only non-null request attributes are permitted");
        requestAttributesHolder.set(attributes);
    }
 
    public static RequestAttributes getRequestAttributes() {
        RequestAttributes attributes = requestAttributesHolder.get();
        if (attributes == null) {
            attributes = new NativeWebRequestAttributes(new MockHttpServletRequest());
            requestAttributesHolder.set(attributes);
        }
        return attributes;
    }
 
    public static void setRequestAttributes(ServletRequest request, ServletResponse response) {
        setRequestAttributes(new ServletWebRequest(request, response));
    }
 
    public static void setRequestAttributes(ServletRequestAttributes attributes) {
        Assert.notNull(attributes, "ServletRequestAttributes must not be null");
        requestAttributesHolder.set(attributes);
    }
 
    public static ServletRequestAttributes getRequestAttributes() {
        RequestAttributes attributes = getRequestAttributes();
        Assert.state(attributes instanceof ServletRequestAttributes,
                "Request attribute does not support request access");
        return (ServletRequestAttributes) attributes;
    }
}

上述代码中,使用ThreadLocal保存请求的信息,如从HttpServletRequest中获取的请求信息,这样可以保证每个线程都能够访问到已绑定请求的信息,线程之间不会相互影响。

2、RequestContextHolder使用InheritableThreadLocal保存请求信息

public class RequestContextHolder {
 
    private static final InheritableThreadLocal requestAttributesHolder =
            new NamedInheritableThreadLocal("Request attributes");
 
    public static void resetRequestAttributes() {
        requestAttributesHolder.remove();
    }
 
    public static void setRequestAttributes(RequestAttributes attributes) {
        Assert.notNull(attributes, "Only non-null request attributes are permitted");
        requestAttributesHolder.set(attributes);
    }
 
    public static RequestAttributes getRequestAttributes() {
        RequestAttributes attributes = requestAttributesHolder.get();
        if (attributes == null) {
            attributes = new NativeWebRequestAttributes(new MockHttpServletRequest());
            requestAttributesHolder.set(attributes);
        }
        return attributes;
    }
 
    public static void setRequestAttributes(ServletRequest request, ServletResponse response) {
        setRequestAttributes(new ServletWebRequest(request, response));
    }
 
    public static void setRequestAttributes(ServletRequestAttributes attributes) {
        Assert.notNull(attributes, "ServletRequestAttributes must not be null");
        requestAttributesHolder.set(attributes);
    }
 
    public static ServletRequestAttributes getRequestAttributes() {
        RequestAttributes attributes = getRequestAttributes();
        Assert.state(attributes instanceof ServletRequestAttributes,
                "Request attribute does not support request access");
        return (ServletRequestAttributes) attributes;
    }
}

与第一种方式不同的是,该代码中使用InheritableThreadLocal保存请求的信息,InheritableThreadLocal是ThreadLocal类的子类,它所保存的值可以被子线程继承,在子线程中可以访问到保存的信息,由于InheritableThreadLocal是可继承的,所以是跨线程的,内存消耗很大,开发时需慎重考虑。

三、RequestContextHolder的用法

1、获取当前请求的HttpServletRequest

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

2、获取当前请求的HttpServletResponse

HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

3、获取当前请求的RequestAttributes

RequestAttributes attributes = RequestContextHolder.getRequestAttributes();

4、通过RequestContextHolder为当前请求创建的子线程传递请求上下文

在多个线程的情况下,如果想把同一个请求传递给同一个线程来进行处理,可以先在原请求线程中获取当前请求上下文,并传递到另外一个线程中,代码示例如下:

原请求线程中:

RequestAttributes attributes = RequestContextHolder.getRequestAttributes();

新线程中:

RequestContextHolder.setRequestAttributes(attributes);

5、在Controller层使用RequestContextHolder的示例:

@RestController
@RequestMapping("/test")
public class TestController {
    @GetMapping("/getRequest")
    public String getRequest(HttpServletRequest request) {
        HttpSession session = request.getSession();
        request.setAttribute("name", "test");
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getAttribute("name").toString();
    }
}

四、小结

RequestContextHolder是Spring框架中作为HTTP请求上下文绑定的持有者,可以方便地随时获取当前请求的HttpServletRequest、HttpServletResponse等信息,能够确保在整个请求处理过程中,我们都能够访问到该请求的相关信息,对Web开发来说非常重要。

原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/311291.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝小蓝
上一篇 2025-01-05 13:23
下一篇 2025-01-05 13:23

相关推荐

  • 神经网络代码详解

    神经网络作为一种人工智能技术,被广泛应用于语音识别、图像识别、自然语言处理等领域。而神经网络的模型编写,离不开代码。本文将从多个方面详细阐述神经网络模型编写的代码技术。 一、神经网…

    编程 2025-04-25
  • Linux sync详解

    一、sync概述 sync是Linux中一个非常重要的命令,它可以将文件系统缓存中的内容,强制写入磁盘中。在执行sync之前,所有的文件系统更新将不会立即写入磁盘,而是先缓存在内存…

    编程 2025-04-25
  • nginx与apache应用开发详解

    一、概述 nginx和apache都是常见的web服务器。nginx是一个高性能的反向代理web服务器,将负载均衡和缓存集成在了一起,可以动静分离。apache是一个可扩展的web…

    编程 2025-04-25
  • 详解eclipse设置

    一、安装与基础设置 1、下载eclipse并进行安装。 2、打开eclipse,选择对应的工作空间路径。 File -> Switch Workspace -> [选择…

    编程 2025-04-25
  • git config user.name的详解

    一、为什么要使用git config user.name? git是一个非常流行的分布式版本控制系统,很多程序员都会用到它。在使用git commit提交代码时,需要记录commi…

    编程 2025-04-25
  • Python输入输出详解

    一、文件读写 Python中文件的读写操作是必不可少的基本技能之一。读写文件分别使用open()函数中的’r’和’w’参数,读取文件…

    编程 2025-04-25
  • Linux修改文件名命令详解

    在Linux系统中,修改文件名是一个很常见的操作。Linux提供了多种方式来修改文件名,这篇文章将介绍Linux修改文件名的详细操作。 一、mv命令 mv命令是Linux下的常用命…

    编程 2025-04-25
  • MPU6050工作原理详解

    一、什么是MPU6050 MPU6050是一种六轴惯性传感器,能够同时测量加速度和角速度。它由三个传感器组成:一个三轴加速度计和一个三轴陀螺仪。这个组合提供了非常精细的姿态解算,其…

    编程 2025-04-25
  • Java BigDecimal 精度详解

    一、基础概念 Java BigDecimal 是一个用于高精度计算的类。普通的 double 或 float 类型只能精确表示有限的数字,而对于需要高精度计算的场景,BigDeci…

    编程 2025-04-25
  • Python安装OS库详解

    一、OS简介 OS库是Python标准库的一部分,它提供了跨平台的操作系统功能,使得Python可以进行文件操作、进程管理、环境变量读取等系统级操作。 OS库中包含了大量的文件和目…

    编程 2025-04-25

发表回复

登录后才能评论