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

相关推荐
ZhengEnCi5 小时前
S02-SpringBoot实体类新增字段对已有数据的影响及自动DDL同步机制详解
数据库·spring boot
程序员张35 小时前
SpringBoot集成BCrypt密码加密库
java·spring boot·后端
闲猫5 小时前
Spring AI Agentic 模式(第1部分):Agent Skills——模块化、可复用的能力
java·人工智能·spring
CaffeinePro5 小时前
FastAPI数据库集成SQLAlchemy异步ORM全方案
后端·fastapi
源图客5 小时前
云途物流API开发-鉴权认证(Java)
java·网络·python
小旭Coding5 小时前
凌晨告警轰炸!Go 服务协程只增不减,内存持续暴涨直至 OOM
后端
半个落月5 小时前
用 LangChain.js 手写一个能读写文件和执行命令的 Mini Cursor
javascript·人工智能·后端
liguojun20255 小时前
篮球馆自动计时收费系统:从规则配置到自动结算的全流程拆解
java·大数据·运维·人工智能·物联网·1024程序员节
952366 小时前
RabbitMQ-基础操作
java·spring boot·分布式·后端·spring·rabbitmq
柒和远方6 小时前
从审计日志到可下载证据包:事务型 Outbox、租约 fencing 与保留水位
前端·后端·架构