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

相关推荐
IT_陈寒20 分钟前
垃圾回收器选错了,我的Java服务内存炸了
前端·人工智能·后端
用户8356290780511 小时前
使用 Python 在 PDF 中创建与管理书签
后端·python
Nturmoils1 小时前
字段太多看不全,ksql 的展开模式和输出控制怎么用
数据库·后端
大志说编程1 小时前
Agent面试真题06: 十分钟带你快速掌握Agent记忆管理高频面试题(附详细答案)
后端·面试·ai编程
ServBay1 小时前
Claude Code 被曝植入后门,AI 时代如何安全打造本地 DevOps
后端·ai编程·claude
王二端茶倒水2 小时前
从千兆到万兆:宽带运营不能只卖套餐,要管用户生命周期从千兆到万兆:宽带运营需要管理用户生命周期
后端·网络协议·架构
网易云信2 小时前
重磅认证!网易智企智能融合通信获鸿蒙生态权威认可,斩获「Harmony Trusted SDK」认证
人工智能·后端·aigc
神奇小汤圆3 小时前
我把祖传Java项目重构后,接口响应从3s砍到了200ms,只改了这几行代码
后端
神奇小汤圆3 小时前
面试官:你们项目里的线程池是怎么用的?怎么管理的?
后端