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

相关推荐
小马爱打代码几秒前
Spring Boot 自动装配流程
java·spring boot·后端
Cosolar4 分钟前
72小时生死时速:一文读懂引爆Fable模型禁令的越狱技术风暴
人工智能·后端·程序员
我登哥MVP6 分钟前
SpringCloud 核心组件解析:分布式配置管理
java·spring boot·分布式·spring·spring cloud·java-ee·maven
lihao lihao7 分钟前
linux线程
java·开发语言·jvm
满怀冰雪8 分钟前
第13篇-栈算法入门-括号匹配-表达式与单调栈基础
java·算法
我是一颗柠檬12 分钟前
【Java项目技术亮点】Redis Lua脚本原子化操作:高并发场景下的终极武器
java·redis·lua
swg32132113 分钟前
Redis实现主从选举
java·前端·redis
砍材农夫15 分钟前
python环境|pip|uv|venv|Conda区别
后端·python·conda·pip·uv
Java 码思客15 分钟前
【ElasticSearch 从入门到架构师】第6章_分词器与文本检索
java·elasticsearch
Flittly16 分钟前
【AgentScope Java新手村系列】(6)Hook与Middleware
java·spring boot·笔记·spring·ai