零、引言

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

public class RequestContextListener implements ServletRequestListener {private static final String REQUEST_ATTRIBUTES_ATTRIBUTE =RequestContextListener.class.getName() + ".REQUEST_ATTRIBUTES";// 在请求进入的时候,初始化变量放入ThreadLocal<T>中
    @Overridepublic void requestInitialized(ServletRequestEvent requestEvent) {//判定当前的requetEvent中获取的ServletRequest()对象是否是HttpServletRequet对象if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) {throw new IllegalArgumentException("Request is not an HttpServletRequest: " + requestEvent.getServletRequest());}//强制转型为 HttpServletRequestHttpServletRequest 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变量清空。
    @Overridepublic 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层获取)。
######################################LiuCF############转载注明出处###############2017年6月22日23:38:49###########################

由SpringMVC中RequetContextListener说起相关推荐

  1. SpringMVC中数据库链接配置

    从昨天开始一直在纠结数据库链接的问题,现在可以说才从库里面查出数据.这种感觉还是希望和大家分享一下 首先我们来看看我用ecplise创建项目的目录结构: 上面是我的目录结构,和数据库链接的都放在了ap ...

  2. SpringMVC中的拦截器

    SpringMVC中的拦截器 拦截器的作用 Spring MVC 的处理器拦截器类似于 Servlet 开发中的过滤器 Filter,用于对处理器进行预处理和后处理. 用户可以自己定义一些拦截器来实现 ...

  3. SpringMVC 中的异常处理

    SpringMVC 中的异常处理 异常处理的思路 系统中异常包括两类:预期异常和运行时异常 RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发.测试通过手段减 ...

  4. SpringMVC中利用HandlerExceptionResolver完成异常处理

    SpringMVC中利用HandlerExceptionResolver完成异常处理 参考文章: (1)SpringMVC中利用HandlerExceptionResolver完成异常处理 (2)ht ...

  5. 在SpringMVC中使用@RequestBody注解处理json时,报出HTTP Status 415的解决方案

    在SpringMVC中使用@RequestBody注解处理json时,报出HTTP Status 415的解决方案 参考文章: (1)在SpringMVC中使用@RequestBody注解处理json ...

  6. springMVC中Dispatcher中的/和/*的区别

    1. 首先 / 这个是表示默认的路径,及表示:当没有找到可以匹配的URL就用这个URL去匹配. 2. 在springmvc中可以配置多个DispatcherServlet,比如: 配置多个Dispat ...

  7. SpringMVC中,前台jsp封装参数,绑定参数,传递参数到后台controller的过程详解

    前台到后台的流程:前台jsp->后台:controller控制器层->service业务层->DAO数据访问层->数据库model模型层. 从上面流程可知,前台jsp的数据,想 ...

  8. springmvc中Controller方法的返回值

    1.1 返回ModelAndView controller方法中定义ModelAndView对象并返回,对象中可添加model数据.指定view. 1.2 返回void 在controller方法形参 ...

  9. SpringMVC 中整合JSON、XML视图一

    SpringMVC中整合了JSON.XML的视图,可以通过这些视图完成Java对象到XML.JSON的转换.转换XML提供了MarshallingView,开发者只需用注入相应的marshaller. ...

最新文章

  1. 【机器学习基础】数学推导+纯Python实现机器学习算法11:朴素贝叶斯
  2. springboot教程(一)
  3. springboot mybatis ehcache_SpringBoot入门建站全系列(十四)集成Redis缓存
  4. zabbix邮件告警
  5. 数据库---练习题(45道)
  6. shell实战之tomcat看门狗
  7. opencv8-图像模糊
  8. 送给程序员:关于性格内向者的10个误解(转)
  9. linux 网络编程
  10. win7网络里计算机登录失败,Win7系统访问网络时提示“登陆失败”的解决方法
  11. 【机器学习】Cross-Validation(交叉验证)详解
  12. 算法资料:算法导论_原书第3版(中文)(PDF带书签)
  13. nodejs安装教程Windows版本
  14. linux7.4邮件服务器,CentOS7 基于Postfix Dovecot Extmail 搭建邮件服务器
  15. HDU1269-迷宫城堡
  16. 仿9GAG制作过程(四)
  17. js每日一题(11)
  18. 订阅内容解码失败(非base64码)_【每日礼包】超杀默示录 密文解码礼包大全
  19. ubuntu 双显卡安装n卡 Quadro K620 Tesla K80*8 显卡驱动的卸载 (已解决)没有图形界面。黑屏
  20. gitee 链接报错

热门文章

  1. 谈谈button标签和input标签的区别
  2. 系统图标及其注册表项
  3. php date函数实现,PHP date() 函数可实现的功能列表
  4. java 优化线程_Java | 多线程调优(下):如何优化多线程上下文切换?
  5. java开发技术有什么意义,零基础学Java开发技术有哪些优势和好处?
  6. python读取python源代码文件_python 读写excel文件操作示例【附源码下载】
  7. 动态获取textarea后面的p标签_HTML简单标签连起实现的小玩意:
  8. zabbix中常用到的几个key:
  9. 为什么选择springcloud微服务架构
  10. 未来的语音世界——中国智能语音市场分析