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

相关推荐
Oneslide8 分钟前
Harbor 启动失败故障排查与解决:从“Cannot allocate memory”到“Operation not permitted”
后端
神超15 分钟前
AgentScope 入门:用 Java 快速搭一个可用的 Agent
后端
steel808816 分钟前
Spring Boot 整合 log4j2 日志配置教程
spring boot·单元测试·log4j
码事漫谈25 分钟前
防患未然,金仓数据库SQL防火墙筑牢数据安全“第一道门”
后端
宸翰28 分钟前
Python学习:年轻人的第一个入门Python项目(FastAPI版)
后端·python
lierenvip30 分钟前
Spring Boot中Tomcat配置
spring boot·tomcat·firefox
Moment30 分钟前
MiniMax 发布 M2.7,Agent 开始走向自我进化
前端·后端·面试
Detachym31 分钟前
InsightFlow 服务配置优化与部署实践
java·spring boot·tomcat·maven·状态模式·jar
rainchestnut32 分钟前
Spring AI 初步集成(1)-初始化
spring boot
y = xⁿ32 分钟前
【LeetCodehot100】T23:合并k个升序链表
java·数据结构·链表