作用:在启动Web容器时,自动装配Spring applicationContext.xml的配置信息。

因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。在ContextLoaderListener中关联了ContextLoader这个类,所以整个加载配置过程由ContextLoader来完成

pring在web下的入口在配置文件web.xml的监听器中

<listener>

<listener-class>

org.springframework.web.context.ContextLoaderListener

</listener-class>

</listener>

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:conf/spring/applicationContext.xml</param-value>

</context-param>

上述是在web.xml中的配置信息。

//实现了接口ServletContextListener,也就是说他必须实现contextDestroyed, contextInitialized这两个方法

publicclass ContextLoaderListener implements ServletContextListener{

privateContextLoader contextLoader;

/**

*Initialize the root web application context.

*/

//Spring框架由此启动, contextInitialized也就是监听器类的main入口函数

publicvoid contextInitialized(ServletContextEvent event) {

this.contextLoader = createContextLoader();

this.contextLoader.initWebApplicationContext(event.getServletContext());

}

/**

* Createthe ContextLoader to use. Can be overridden in subclasses.

* @returnthe new ContextLoader

*/

protectedContextLoader createContextLoader() {

return new ContextLoader();

}

/**

* Returnthe ContextLoader used by this listener.

* @returnthe current ContextLoader

*/

publicContextLoader getContextLoader() {

return this.contextLoader;

}

/**

* Closethe root web application context.

*/

publicvoid contextDestroyed(ServletContextEvent event) {

if (this.contextLoader != null) {

this.contextLoader.closeWebApplicationContext(event.getServletContext());

}

}

}

总的来说这个入口非常简单,所有实现都隐藏在ContextLoader类里,我们在下一篇的内容中讨论ContextLoader,如果你不知道为什么这里是程序的入口,那么复习一下ServletContextListener接口和监听器的相关知识吧

ServletContext 被Servlet 程序用来与 Web 容器通信。例如写日志,转发请求。每一个 Web 应用程序含有一个Context,被Web应用内的各个程序共享。因为Context可以用来保存资源并且共享,所以我所知道的 ServletContext 的最大应用是Web缓存----把不经常更改的内容读入内存,所以服务器响应请求的时候就不需要进行慢速的磁盘I/O了。

ServletContextListener 是ServletContext 的监听者,如果 ServletContext 发生变化,如服务器启动时 ServletContext 被创建,服务器关闭时 ServletContext 将要被销毁。

在JSP文件中,application 是 ServletContext 的实例,由JSP容器默认创建。Servlet 中调用 getServletContext()方法得到 ServletContext 的实例。

我们使用缓存的思路大概是:

1. 服务器启动时,ServletContextListener 的contextInitialized()方法被调用,所以在里面创建好缓存。可以从文件中或者从数据库中读取取缓存内容生成类,用 ervletContext.setAttribute()方法将缓存类保存在ServletContext 的实例中。

2. 程序使用 ServletContext.getAttribute()读取缓存。如果是 JSP,使用a pplication.getAttribute()。如果是 Servlet,使用 getServletContext().getAttribute()。如果缓存发生变化(如访问计数),你可以同时更改缓存和文件/数据库。或者你等 变化积累到一定程序再保存,也可以在下一步保存。

3. 服务器将要关闭时,ServletContextListener 的 contextDestroyed()方法被调用,所以在里面保存缓存的更改。将更改后的缓存保存回文件或者数据库,更新原来的内容。

Java代码  

  1. import User; //my own
  2. classimport DatabaseManager; // my own class
  3. import javax.servlet.ServletContext;
  4. import javax.servlet.ServletContextListener;
  5. public class MyContextListener  implements ServletContextListener {
  6. private ServletContext context = null;
  7. public void contextInitialized(ServletContextEvent event) {
  8. context = event.getServletContext();
  9. User user = DatabaseManager.getUserById(1);
  10. context.setAttribute("user1", user);
  11. }
  12. public void contextDestroyed(ServletContextEvent event) {
  13. User user = (User)context.getAttribute("user1");
  14. DatabaseManager.updateUserData(user);
  15. this.context = null;
  16. }
  17. }

import User; //my own

classimport DatabaseManager; //my own class

importjavax.servlet.ServletContext;

importjavax.servlet.ServletContextListener;

public classMyContextListener  implementsServletContextListener {

private ServletContext context = null;

public voidcontextInitialized(ServletContextEvent event) {

context =event.getServletContext();

User user =DatabaseManager.getUserById(1);

context.setAttribute("user1", user);

}

public voidcontextDestroyed(ServletContextEvent event) {

User user =(User)context.getAttribute("user1");

DatabaseManager.updateUserData(user);

this.context = null;

}

}

布署 ServletContextListener

你实现(implements)了 ServletContextListener 编译后,把它放在正确的WEB-INF/classes目录下,更改WEB-INF目录下的 web.xml文件,在web-app节点里添加

<listener>

<listener-class>MyServletContextListener</listener-class>

</listener>

----------------------------------------在不同的情况下获取数据-----------------------------------------

spring  task定时器类中:

   实现ApplicationContextAware接口
public class a implements ServletContextAware {
           private ServletContext servletContext;

@Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    public void b() {
servletContext.getAttribute("uid")
     }}

controller 类中:
   ServletContext servletContext=request.getSession().getServletContext();
  servletContext.getAttribute("uid");

java普通类中:

只能从controller 传 servletContext或者仿照task类的方式

spring项目中监听器作用-ContextLoaderListener(项目启动时,加载一些东西到缓存中)的更多相关文章

  1. web.xml中配置启动时加载的servlet,load-on-starup

    web.xml中配置启动时加载的servlet,load-on-starup 使用servlet来初始化配置文件数据: 在servlet的配置当中,<load-on-startup>1&l ...

  2. 基于Spring MVC的web应用随应用启动而加载

    写个类实现org.springframework.context.ApplicationContextAware接口即可. 但是如下的程序会在启动时加载两次: @Controller public c ...

  3. Servlet在启动时加载的tomcat源码(原创)

    tomcat 8.0.36 知识点: 通过配置loadOnStartup可以设置Servlet是否在Tomcat启动时加载,以及按值大小进行有序加载,其最小有效值为0,最大有效值为Integer.MA ...

  4. ElasticSearch 启动时加载 Analyzer 源码分析

    ElasticSearch 启动时加载 Analyzer 源码分析 本文介绍 ElasticSearch启动时如何创建.加载Analyzer,主要的参考资料是Lucene中关于Analyzer官方文档 ...

  5. 设置程序启动时加载的storyboard

    这个设置表明:程序启动时会加载Main.storyboard

  6. spring项目中监听器作用-ContextLoaderListener(转)

    1 spring框架的启动入口 ContextLoaderListener 2 作用:在启动Web 容器时,自动装配Spring applicationContext.xml 的配置信息. 因为它实现 ...

  7. spring项目中监听器作用-ContextLoaderListener

    附加链接:http://blog.csdn.net/zjw10wei321/article/details/40145241 作用:在启动Web 容器时,自动装配Spring applicationC ...

  8. 依赖Spring的情况下,Java Web项目如何在启动时加载数据库中的数据?

    原文:https://blog.csdn.net/u012345283/article/details/39558537 原文:https://blog.csdn.net/wandrong/artic ...

  9. Tomcat启动时加载数据到缓存---web.xml中listener加载顺序(优先初始化Spring IOC容器)

    JavaWebSpringTomcatCache  最近用到在Tomcat服务器启动时自动加载数据到缓存,这就需要创建一个自定义的缓存监听器并实现ServletContextListener接口,并且 ...

随机推荐

  1. 武汉科技大学ACM:1009: 华科版C语言程序设计教程(第二版)习题5.12

    Problem Description 这天老师照例给小豪出了一道题目:老师给小豪一个字符串,让小豪将该字符串逆序输出. Input 第一行包括一个T,表示有多少组测试数据: 接下来T行,每行包括一个 ...

  2. 武汉科技大学ACM :1005: 一二三

    Problem Description 你弟弟刚刚学会写英语的一(one).二(two)和三(three).他在纸上写了好些一二三,可惜有些字母写错了.已知每个单词最多有一个字母写错了(单词长度肯定不 ...

  3. javascript回调函数

    function $$(f) { if (typeof f == 'function') {//f是一个函数 f(); } else { alert('not a function'); } } $$ ...

  4. Pyhton 操作MySQL数据库

         MySQL数据库的接口程序下载地址:https://sourceforge.net/projects/mysql-python/ 操作数据库的大致步骤如下: 1:首先先创建一个数据库的连接对 ...

  5. 《python基础教程》笔记之 序列通用操作

    索引 序列中的所有元素都是有编号的--从0开始递增.使用负数索引时,Python会从右边,也就是从最后一个元素开始计数,最后一个元素的位置编号是-1.此外,字符串是一个有字符组成的序列,字符串字面值可 ...

  6. 魔法方法:算术运算 - 零基础入门学习Python042

    魔法方法:算术运算 让编程改变世界 Change the world by program 我现在重新提一个名词:工厂函数,不知道大家还有没有印象?我们在老早前就提到过Ta,由于那时候我们还没有学习类 ...

  7. 無心插柳的Linux學習者代言人——蔡德明

    誰是「蔡德明」恐怕沒有多少人知道,不過提到「鳥哥」這個稱號,在臺灣的Linux社群幾乎是無人不知無人不曉,蔡德明正是鳥哥的本名.鳥哥究竟多有名? 如果你是有意學習Linux的初學者,卻不知如何下手,1 ...

  8. 转:pthread_detach()函数

    创建一个线程默认的状态是joinable. 如果一个线程结束运行但没有被join,则它的状态类似于进程中的Zombie Process,即还有一部分资源没有被回收(退出状态码). 所以创建线程者应该调 ...

  9. ng-options

    tr td 地点 td select.form-control(required="true" ng-model="addkc.dd" ng-options=& ...

  10. DUBBO安装配置注意事项

    DUBBO安装配置注意事项 参考URL:http://blog.csdn.net/lichunan/article/details/40349645 ====== 管理端: 记得更改TOMCAT的端口 ...