1.原理分析:
RequestContextListener用于监听用户的请求,当一个用户发送一个请求,会将用户的请求request对象保存在RequestContextHolder中的requestAttributesHolder本地线程池中,当用户的请求执行完毕,会清除RequestContextHolder中的requestAttributesHolder本地线程池中的request对象
2.应用场景:
①在web.xml中配置RequestContextListener监听器
②在代码中的任何地方,比如controller、service等中可以通过如下方式获取request对象
public static HttpServletRequest getRequest() {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
return request;
}
3.源码分析: RequestContextListener类
用户发送请求会执行requestInitialized方法,然后通过如上图箭头标记的地方设置ServletRequestAttributes,然后点击setRequestAttributes方法我们得到如下图
点击方法进入如下图
执行如上图标记的地方,继续点击进去
如上图我们可以看到,该方法会获取当前请求的线程,当前请求的线程Thread对象中包含一个ThreadLocalMap,如果当前线程的ThreadLocalMap为null,则创建一个,会将RequestContextHolder中的requestAttributesHolder对象作为key,ServletRequestAttributes对象作为value。
这样我们通过RequestContextHolder中的getRequestAttributes方法获取request对象
之后附上SevletRequestListener被注册的地方
1.Spring项目中我们需要在web.xml中配置RequestContextListener监听器来监听用户的请求
2.Spring boot项目我们可以直接使用,原因如下图,已经帮助我们自动注册了改监听器
来源:[]()