Spring boot 之RequestContextHolder读取

本文介绍了在Spring Boot应用中如何利用RequestContextHolder获取请求的request和response对象。通过RequestContextHolder的静态方法可以方便地访问Request相关变量。原理涉及ThreadLocal,它确保了数据在本地线程内的可见性,并在线程结束时自动回收。当遇到空指针异常时,可能需要在配置类中注册RequestContextListener bean。
摘要由CSDN通过智能技术生成

在spring boot中,为了随时都能取到当前请求的request对象,可以通过RequestContextHolder的静态方法getRequestAttributes()获取Request相关的变量,如request, response等。如下:

public static HttpServletRequest getRequest() {

return 
 ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

}

是什么原因,可以让我们随时都能取出request或者response对象呢,猜测是存在ThreadLocal:本地线程变量,存储在这个里面的数据可以在整个线程期都可见,线程一旦执行完成就回收,具体源码如下:

public abstract class RequestContextHolder  {

	private static final boolean jsfPresent =
			ClassUtils.isPresent("javax.faces.context.FacesContext", RequestContextHolder.class.getClassLoader());

	private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
			new NamedThreadLocal<RequestAttributes>("Request attributes");

	private static final ThreadLocal<RequestAt
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值