SpringBoot 获取HttpServletRequest

方式一:Controller方法参数

@GetMapping("/test")
public void test(HttpServletRequest request) {}

方式二:通过RequestContextHolder手动获取

@GetMapping("/test")
public void test(HttpServletRequest request) {
   	// 从请求上下文里获取Request对象
    ServletRequestAttributes requestAttributes = ServletRequestAttributes.class.
        cast(RequestContextHolder.getRequestAttributes());
    HttpServletRequest contextRequest = requestAttributes.getRequest(); 
    或者
    HttpServletRequest request = ((ServletRequestAttributes)         
    (RequestContextHolder.currentRequestAttributes())).getRequest();
 
}

​RequestContextHolder内部是使用ThreadLocal来维护Request的,线程间隔离,所以不存在线程安全问题,这样使用是没有问题的。

方式三:自动注入@Autowired

    @Autowired
    HttpServletRequest httpServletRequest;

    @GetMapping("/hello")
    public String hello() {
        
        return "hello:" + simpleDateFormat.format(new Date());
    }

tomcat是多线线程的,通过@Autowired注入的Request对象虽然看起是一个全局的共享变量,但是它实际上却是线程安全的。Spring底层通过一个代理对象让客户端去操作了ThreadLocal中的request,即每个线程都只操作自己的request,是线程隔离的,所以也就不存在并发安全问题了。

参考:

从Spring源码分析@Autowired注入的request是否线程安全_程序员小潘的博客-CSDN博客_autowired 线程安全

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值