来自:https://www.cnblogs.com/softidea/p/7068196.html

零、引言

RequetContextListener从名字结尾Listener来看就知道属于监听器。
所谓监听器就是监听某种动作,在其开始(初始化)和结束(销毁)的时候进行某些操作。
由此可以猜测:该类用于在RequetContext(请求上下文对象)创建和销毁的时候进行某些操作(哪些操作?结尾总结!)

一、web.xml配置

要使用该listener对象需要在web.xml中进行如下配置。
<!-- 此监听器是监听HttpRequest对象,方便ContextHolderUtils程序调用HttpRequest对象 -->
<listener>
<description>request监听器</description>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

二、三个重要类解读

2.1 RequetContextListener

  //ServletRequestListener web中的监听器,该监听器主要在创建request,销毁request对象起作用
public class RequestContextListener implements ServletRequestListener {
private static final String REQUEST_ATTRIBUTES_ATTRIBUTE =
RequestContextListener.class.getName() + ".REQUEST_ATTRIBUTES";
// 在请求进入的时候,初始化变量放入ThreadLocal<T>中 ,创建request对象
@Override
public void requestInitialized(ServletRequestEvent requestEvent) {
//判定当前的requetEvent中获取的ServletRequest()对象是否是HttpServletRequet对象
if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) {
throw new IllegalArgumentException(
"Request is not an HttpServletRequest: " + requestEvent.getServletRequest());
}
//强制转型为 HttpServletRequest
HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest();
// ServletRequestAttributes 保存了HttpServletRequet、Response、Session等变量
ServletRequestAttributes attributes = new ServletRequestAttributes(request);
request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes);
LocaleContextHolder.setLocale(request.getLocale());
//RequestContextHolder里面有一个ThreadLocal,当前线程共享
RequestContextHolder.setRequestAttributes(attributes);
}
//在请求被销毁的时候,将在初始化时候的ThreadLocal变量清空。
@Override
public void requestDestroyed(ServletRequestEvent requestEvent) {
...
}
}

2.2 RequetContextHolder

public abstract class RequestContextHolder  {
//ThreadLocal<T>变量用于保存当前线程的共享变量
private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
new NamedThreadLocal<RequestAttributes>("Request attributes");
private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder =
new NamedInheritableThreadLocal<RequestAttributes>("Request context");
/**
* 将线程中的共享变量清除掉,会在RequetContextListner的destory()方法中调用。
*/
public static void resetRequestAttributes() {
//清空变量
requestAttributesHolder.remove();
inheritableRequestAttributesHolder.remove();
}
//过渡方法
public static void setRequestAttributes(RequestAttributes attributes) {
setRequestAttributes(attributes, false);
}
// 核心的方式:将RequetAttrubutes(Request/Response/Session)放入到ThreadLocal<T>中进行共享
public static void setRequestAttributes(RequestAttributes attributes, boolean inheritable) {
if (attributes == null) {
resetRequestAttributes();
}
else {
if (inheritable) {
inheritableRequestAttributesHolder.set(attributes);
requestAttributesHolder.remove();
}
else {
requestAttributesHolder.set(attributes);
inheritableRequestAttributesHolder.remove();
}
}
}

2.3 ServletRequestAttributes

public class ServletRequestAttributes extends AbstractRequestAttributes {
private final HttpServletRequest request;
private HttpServletResponse response;
private volatile HttpSession session;
private final Map<String, Object> sessionAttributesToUpdate = new ConcurrentHashMap<String, Object>(1);
}

三、使用方法

从以上可以知道RuquetAttribute是放在了ThreadLocal中,则在该次请求中,可以在任意的代码位置中获取该该对象,由此拿到HttpServletRequet等对象。
HttpServletRequest request =((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
利用该方法可以在任意位置获取request对象.

四、总结

RequetContextListner主要作用就一个:
将本次请求的 ServletRequestAttributes 对象 保存在ThreadLocal中,方便在某一次请求的任意代码位置获取(包括直接在service层获取)。

SpringMVC中RequetContextListener的更多相关文章

  1. 由SpringMVC中RequetContextListener说起

    零.引言 RequetContextListener从名字结尾Listener来看就知道属于监听器. 所谓监听器就是监听某种动作,在其开始(初始化)和结束(销毁)的时候进行某些操作. 由此可以猜测:该 ...

  2. SpringMvc中的数据校验

    SpringMvc中的数据校验 Hibernate校验框架中提供了很多注解的校验,如下: 注解 运行时检查 @AssertFalse 被注解的元素必须为false @AssertTrue 被注解的元素 ...

  3. 【Spring】SpringMVC中浅析Date类型数据的传递

    在控制器中加入如下代码: @InitBinder public void initBinder(ServletRequestDataBinder bin){ SimpleDateFormat sdf ...

  4. 详解SpringMVC中GET请求

    GET请求概述 GET请求,请求的数据会附加在URL之后,以?分割URL和传输数据,多个参数用&连接.URL的编码格式采用的是ASCII编码,而不是uniclde,所有的非ASCII字符都要编 ...

  5. SpringMVC中使用Interceptor拦截器

    SpringMVC 中的Interceptor 拦截器也是相当重要和相当有用的,它的主要作用是拦截用户的请求并进行相应的处理.比如通过它来进行权限验证,或者是来判断用户是否登陆,或者是像12306 那 ...

  6. 如何在springMVC 中对REST服务使用mockmvc 做测试

    如何在springMVC 中对REST服务使用mockmvc 做测试 博客分类: java 基础 springMVCmockMVC单元测试  spring 集成测试中对mock 的集成实在是太棒了!但 ...

  7. springMVC 返回类型选择 以及 SpringMVC中model,modelMap.request,session取值顺序

    springMVC 返回类型选择 以及 SpringMVC中model,modelMap.request,session取值顺序 http://www.360doc.com/content/14/03 ...

  8. SpringMVC中使用Cron表达式的定时器

    SpringMVC中使用Cron表达式的定时器 cron(定时策略)简要说明 顺序: 秒 分 时 日 月 星期 年份 (7个参数,空格隔开各个参数,年份非必须参数) 通配符: , 如果分钟位置为* 1 ...

  9. SpringMVC中使用Json传数据

    在web项目中使用Json进行数据的传输是非常常见且有用的,在这里介绍下在SpringMVC中使用Json传数据的一种方法,在我的使用中,主要包括下面四个部分(我个人喜好使用maven这类型工具进行项 ...

随机推荐

  1. 22、linux的ssh互信配置

    转载:https://blog.csdn.net/hrn1216/article/details/51568830 https://blog.csdn.net/u013144287/article/d ...

  2. 4、Brief primer and lexicon for PacBio SMRT sequencing

    转载:http://pacbiofileformats.readthedocs.io/en/5.1/Primer.html 转载:http://pacbiofileformats.readthedoc ...

  3. Gym - 100792C Colder-Hotter(三分交互)

    Colder-Hotter Statements This is an interactive problem. Egor and Petr are playing a game called «Co ...

  4. i++,++i,i+=1,i = i+1在C++中的区别

    其实这个问题可以从三个角度去分析:语言规范,编译器实现,CPU支持.首先从语言规范上来讲:前置++和后置++是不等价的,前置++在规范中明确指出 和+=组合操作符是等价的,但和E = E+1;这样的赋 ...

  5. How can I list colors in WPF with XAML?

    How can I get list of all colors I can pick in Visual Studio Designer (which is System.Windows.Media ...

  6. Core中间件——访问记录

    引言 上半年使用的thinkjs开发的node项目有一个优点就是所有请求都会有日志记录在控制台输出,里面包含了请求地址以及耗时.我就希望在.net中也可以实现这样子的功能,正好想到了中间件,所以就用中 ...

  7. Go语言环境安装-Mac

    1.环境安装 Go SDK下载和安装,下载地址为:https://golang.org/dl/ Visual Studio Code下载和安装,下载地址为:https://code.visualstu ...

  8. GitHub下载代码到本地

    1.git  clone git@github.com:Sehunwy/test.git(加粗的是下载的地址) 2.下载完成,此时本地是这样的: 参考:https://blog.csdn.net/qq ...

  9. CS基本网络中Agent使用双网卡进行流量划分

    两台服务器,一台服务器作为管理节点[单网卡],一台服务器作为计算节点[双网卡] ------------------------------------------------------------ ...

  10. [SinGuLaRiTy] NOIP膜你赛-Day 1

    [SinGuLRiTy-1022] Copyright (c) SinGuLaRITy 2017. All Rights Reserved.  对于所有题目:Time Limit:1s || Memo ...