RequestContextHolder

道哥走天下 / 2024-10-12 / 原文

官方api说明 没有找到教程

https://www.jianshu.com/p/7b0dc8c9090e

一、RequestContextHolder简析

在Web开发中,service层或者某个工具类中需要获取到HttpServletRequest对象还是比较常见的。一种方式是将HttpServletRequest作为方法的参数从controller层一直放下传递,不过这种有点费劲,且做起来不是优雅;还有另一种则是RequestContextHolder,直接在需要用的地方使用如下方式取HttpServletRequest即可。

二、RequestContextHolder的使用

RequestContextHolder顾名思义,持有上下文的Request容器.使用是很简单的,具体使用如下:

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

三、常见问题

  1. 空指针问题
    启动类添加配置:
    @Bean
    public RequestContextListener requestContextListener(){
        return new RequestContextListener();
    }