04-springmvc-RequestContextHolder

一、获取request对象的四种方法

方法1、Controller中加参数来获取request

注意只能在Controller中加入request参数

一般,我们在Controller中加参数获取HttpServletRequest,如下所示:

java 复制代码
@RestController
@RequestMapping("/lxx")
public class PlantTraceController {
    @PostMapping("/plantTrace")
    public Result2 savePlantTraceInfo(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        String methodName = request.getHeader("methodName");
        ....
}

该方法实现的原理是,在Controller方法开始处理请求时,Spring会将request对象赋值到方法参数中。此时request对象是方法参数,相当于局部变量,毫无疑问是线程安全的。

Controller中获取request对象后,如果要在其他方法中(如service方法、工具类方法等)使用request对象,需要在调用这些方法时将request对象作为参数传入。

优缺点

这种方法的主要缺点是request对象写起来冗余太多,主要体现在两点:

  1. 如果多个controller方法中都需要request对象,那么在每个方法中都需要添加一遍request参数

  2. request对象的获取只能从controller开始,如果使用request对象的地方在函数调用层级比较深的地方,那么整个调用链上的所有方法都需要添加request参数

实际上,在整个请求处理的过程中,request对象是贯穿始终的;也就是说,除了定时器等特殊情况,request对象相当于线程内部的一个全局变量。而该方法,相当于将这个全局变量,传来传去。

方法2、自动注入来获取request

注意只能在Bean中注入request

java 复制代码
@Controller
public class TestController{
    @Autowired
    private HttpServletRequest request; //自动注入request
    @RequestMapping("/test")
    public void test() throws InterruptedException{
        //模拟程序执行了一段时间
        Thread.sleep(1000);
    }
}

优缺点

该方法的主要优点:

  1. 注入不局限于Controller中:在方法1中,只能在Controller中加入request参数。而对于方法2,不仅可以在Controller中注入,还可以在任何Bean中注入,包括Service、Repository及普通的Bean。

  2. 注入的对象不限于request:除了注入request对象,该方法还可以注入其他scope为request或session的对象,如response对象、session对象等;并保证线程安全。

  3. 减少代码冗余:只需要在需要request对象的Bean中注入request对象,便可以在该Bean的各个方法中使用,与方法1相比大大减少了代码冗余。

但是,该方法也会存在代码冗余。考虑这样的场景:web系统中有很多controller,每个controller中都会使用request对象(这种场景实际上非常频繁),这时就需要写很多次注入request的代码;如果还需要注入response,代码就更繁琐了。下面说明自动注入方法的改进方法,并分析其线程安全性及优缺点。

方法3:基类中自动注入(推荐)

注意只能在Bean中注入request

与方法2相比,将注入部分代码放入到了基类中。

基类代码:

java 复制代码
public class BaseController {
    @Autowired
    protected HttpServletRequest request;     
}

优缺点

与方法2相比,避免了在不同的Controller中重复注入request;但是考虑到java只允许继承一个基类,所以如果Controller需要继承其他类时,该方法便不再好用。

论是方法2和方法3,都只能在Bean中注入request;如果其他方法(如工具类中static方法)需要使用request对象,则需要在调用这些方法时将request参数传递进去。下面介绍的方法4,则可以直接在诸如工具类中的static方法中使用request对象(当然在各种Bean中也可以使用)。

方法4:从RequestContextHolder中获取request

代码示例

java 复制代码
@Controller
public class TestController {
    @RequestMapping("/test")
    public void test() throws InterruptedException {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        // 模拟程序执行了一段时间
        Thread.sleep(1000);
    }
}

优缺点

优点:可以在非Bean中直接获取。缺点:如果使用的地方较多,代码非常繁琐;因此可以与其他方法配合使用。

二、RequestContextHolder详解

1、RequestContextHolder的使用

java 复制代码
//两个方法在没有使用JSF的项目中是没有区别的
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
//RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

//从session里面获取对应的值
String name = (String) requestAttributes.getAttribute("name", RequestAttributes.SCOPE_SESSION);

//类型转换
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)requestAttributes;

//获取到Request对象
HttpServletRequest request = servletRequestAttributes.getRequest();
//获取到Response对象
HttpServletResponse response = servletRequestAttributes.getResponse();
//获取到Session对象
HttpSession session = request.getSession();

2、实现原理

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

java 复制代码
private static final ThreadLocal<RequestAttributes> requestAttributesHolder = new NamedThreadLocal("Request attributes");
private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder = new NamedInheritableThreadLocal("Request context");

设置方法

java 复制代码
 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设置进去的

java 复制代码
 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);
        }

    }

再看一下请求信息怎么获取

java 复制代码
 @Nullable
    public static RequestAttributes getRequestAttributes() {
        RequestAttributes attributes = (RequestAttributes)requestAttributesHolder.get();
        if (attributes == null) {
            attributes = (RequestAttributes)inheritableRequestAttributesHolder.get();
        }

        return attributes;
    }
相关推荐
彭于晏Yan9 小时前
Springboot实现微服务监控
spring boot·后端·微服务
小江的记录本9 小时前
【Spring Boot—— .yml(YAML)】Spring Boot中.yml文件的基础语法、高级特性、实践技巧
xml·java·spring boot·后端·spring·spring cloud·架构
爱敲代码的小黄9 小时前
Agent 能力模块化:Skill 设计与执行机制解析
人工智能·后端·面试
掘金者阿豪9 小时前
告别SQL性能焦虑:金仓数据库“连接条件下推”的性能魔法
后端
老友@10 小时前
接口调用的演进史——从“发 HTTP 请求”到“可治理的系统能力
spring boot·后端·架构
zzb158010 小时前
RAG from Scratch-优化-routing
java·前端·网络·人工智能·后端·python·mybatis
酱紫学Java10 小时前
数据安全比赛:Python 内置函数实战指南
后端·python·网络安全
程途知微11 小时前
Java 内存模型 (JMM) 与 volatile 底层实现
java·后端
手握风云-11 小时前
Spring AI:让大模型住进 Spring 生态(二)
java·后端·spring
不会写DN11 小时前
Golang中实时推送的功臣 - WebSocket
开发语言·后端·golang