SpringBoot 如何获取HttpServletRequest 简称 Request对象

SpringBoot 如何获取HttpServletRequest 对象

  • [1、通过请求参数中获取 Request 对象](#1、通过请求参数中获取 Request 对象)
  • [2、通过 RequestContextHolder 获取 Request 对象](#2、通过 RequestContextHolder 获取 Request 对象)
  • [3、通过自动注入获取 Request 对象](#3、通过自动注入获取 Request 对象)

1、通过请求参数中获取 Request 对象

2、通过 RequestContextHolder 获取 Request 对象

RequestContextHolder顾名思义,持有上下文的Request容器

先将 request 和 response 封装到 ServletRequestAttributes。再将ServletRequestAttributes绑定到RequestContextHolder类的两个ThreadLocal中,从而通过ThreadLocal的get方法获取ServletRequestAttributes。

java 复制代码
@RequestMapping("/index")
@ResponseBody
public void index(){
	ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
	HttpServletRequest request = servletRequestAttributes.getRequest();
	// do something
}

3、通过自动注入获取 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,代码就更繁琐了。下面说明自动注入方法的改进方法,并分析其线程安全性及优缺点。

相关推荐
软件技术NINI3 分钟前
基于 SpringBoot 的酒店预定系统
java·spring boot·后端
利威尔xu21 分钟前
Go context取消传播3层:信号传不到第3层goroutine,泄漏拖垮
后端·golang
软件技术NINI26 分钟前
基于 Spring Boot 中国历史知识学习系统
spring boot·后端·学习
田里的水稻1 小时前
FA_排序算法-冒泡排序
java·算法·排序算法
Coder_shen2 小时前
西门子S7-300-400系列PLC-S7comm协议通信驱动的CSharp实现
后端
她的男孩2 小时前
会签选了候选角色,发起却报 nrOfInstances:Forge Admin 改成按人展开集合
spring boot·低代码·工作流引擎
泡海椒2 小时前
Java 生成应急事件地图 PDF:jquick-pdf 地域分布报表的模板逐行解剖
后端
DaZiDian2 小时前
手动拆解 QQ SQLCipher
后端
bai2732 小时前
*.js 匹配到了 B.JS:fs.globSync 在 Windows 上的五个默认值
javascript·后端
geovindu2 小时前
python: Decision Tree
开发语言·后端·python·决策树