一. Listener 介绍

Servlet API提供了大量监听器来监听web应用的的内部事件,从而允许当web内部事件发生时回调事件监听器内的方法。

使用listener分为两步

  1. 定义LIstener实现类
  2. 通过注解或在web.xml文件中配置Listener

1.1 实现listener类

常用的web时间监听接口有如下几个。

  • ServletContextListener:用于监听应用的启动和关闭
  • ServletContextAttributeLIstener:用于监听ServletContext(application)范围属性的改变
  • ServletRequestListener:用于监听用户请求
  • ServletRequestAttributeListener:用于监听HttpServletRequest(equest)范围属性的改变
  • HttpSessionListener:用于监听用户Session的开始和结束
  • HttpSessionAttributeListener:用于监听HttpSession(session)范围的属性的改变

下面先以ServletContextListener为例来介绍Listener的开发和使用。该listener实现了ServletContextListener接口,该接口包含如下两个方法。

  • contextInitialized(ServletContextEvent sce):启动web应用时,系统调用Listener的该方法
  • contextDestroy(ServletContextEvent sce):关闭web应用时,系统调用Listener的该方法

下面创建一个获取数据库连接的Listener,该Listener会在应用启动时获取数据库连接,并将获取到的连接设置为application的属性。

@WebListener()
public class GetConnListener implements ServletContextListener{ // Public constructor is required by servlet spec
public GetConnListener() {
} // -------------------------------------------------------
// ServletContextListener implementation
// -------------------------------------------------------
public void contextInitialized(ServletContextEvent sce) {
/* This method is called when the servlet context is
initialized(when the Web application is deployed).
You can initialize servlet context related data here.
*/
try{
ServletContext application = sce.getServletContext(); String driver = application.getInitParameter("driver");
String url = application.getInitParameter("url");
String user = application.getInitParameter("user");
String pass= application.getInitParameter("pass"); Class.forName(driver);
Connection conn = DriverManager.getConnection(url,user,pass);
application.setAttribute("conn",conn);
}catch(Exception e)
{
System.out.println("系统获取数据库连接时出现异常"+e.getMessage());
}
} public void contextDestroyed(ServletContextEvent sce) {
/* This method is invoked when the Servlet Context
(the Web application) is undeployed or
Application Server shuts down.
*/
ServletContext application = sce.getServletContext();
Connection conn = (Connection)application.getAttribute("conn");
if(conn != null){
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
} }
}

1.2 配置Listener

配置Listener十分简单,有两种方式

  • 使用@WebListener修饰Listener实现类,无需指定任何属性
  • 在web.xml文件中使用<listener.../>子元素配置
    <!--配置Listener的实现类-->
    <listener>
    <listener-class>java.gdut.Listener.GetConnListener</listener-class>
    </listener>

二. 一些常用的监听器和它们常用的方法

2.1 使用ServletContextAttributeListener

ServletContextAttributeListener用于监听ServletContext(application)范围属性的变化

它包含如下三个方法

  • attributeAdd(ServletContextAttributeEven e):当程序把一个属性存入application范围时触发该方法
  • attributeRemoved(ServletContextAttributeEven e):当程序把一个属性从application范围删除时触发该方法
  • attributeReplaced(ServletContextAttributeEven e):当程序更换application范围属性时触发该方法

2.2 使用ServletRequestListener和ServletRequestAttributeListener

ServletRequestListener用于监听用户请求的到达,实现该接口的实现类需要实现以下两个方法

  • requestInitialized(ServletRequestEven sre):用户请求到达,被初始化时触发该方法。
  • requestDestroy(ServletRequestEven sre):用户请求结束,被销毁时触发该方法

ServletRequestAttributeListener用于监听ServletRequest(request)范围属性的变化

  • attributeAdd(ServletRequestAttributeEven e):当程序把一个属性存入request范围时触发该方法
  • attributeRemoved(ServletRequestAttributeEven e):当程序把一个属性从request范围删除时触发该方法
  • attributeReplaced(ServletRequestAttributeEven e):当程序更换request范围属性时触发该方法

2.3 使用HttpSessiontListener和HttpSessionAttributeListener

HttpSessionListener用于监听用户session的创建和销毁,实现接口的监听器需要实现如下两个方法。

  • sessionCreated(HttpSession se):用户与服务器的会话开始,创建时触发该方法
  • sessionDestroy(HttpSession se):用户与服务器断开,销毁时触发该方法

HttpSessionAttributeListener用于监听HttpSession(session)范围的属性的变化,实现接口的监听器需要实现如下三个方法。

  • attributeAdd(HttpSessionAttributeEven e):当程序把一个属性存入session范围时触发该方法
  • attributeRemoved(HttpSessionAttributeEven e):当程序把一个属性从session范围删除时触发该方法
  • attributeReplaced(HttpSessionAttributeEven e):当程序更换session范围属性时触发该方法

实现HttpSessionListener接口的监听器可以监听每个用户的会话的开始和断开,因此应用可以通过监听器监听系统的在线用户。

@WebListener()
public class OnlineListener implements HttpSessionListener { // -------------------------------------------------------
// HttpSessionListener implementation
// -------------------------------------------------------
public void sessionCreated(HttpSessionEvent se) {
/* Session is created. */
HttpSession session = se.getSession();
ServletContext application = session.getServletContext();
String sessionId = session.getId();
if(session.isNew()){
String user = (String)session.getAttribute("user");
user = (user == null)?"游客":"user";
Map<String,String> online = (Map<String,String>)application.getAttribute("online");
if(online == null){
online = new Hashtable<String,String>();
}
online.put(sessionId,user);
application.setAttribute("online",online);
} } public void sessionDestroyed(HttpSessionEvent se) {
/* Session is destroyed. */
HttpSession session = se.getSession();
ServletContext application = session.getServletContext();
String sessionId = session.getId();
Map<String,String> online = (Map<String,String>)application.getAttribute("online");
if(online != null){
online.remove(sessionId);
}
application.setAttribute("online",online);
} }

初学Listener的更多相关文章

  1. ORACLE清理、截断监听日志文件(listener.log)

    在ORACLE数据库中,如果不对监听日志文件(listener.log)进行截断,那么监听日志文件(listener.log)会变得越来越大,想必不少人听说过关于"LISTENER.LOG日 ...

  2. 使用Maven构建javaWeb项目时,启动tomcat出错:严重: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener java.lang.ClassNotFoundException: org.springframework.web.conte

    在初学使用maven构建javaWeb的项目的时候,启动tomcat加载时,总是提示如下错误,辛苦一番终于找到解决办法. 严重: Error configuring application liste ...

  3. DDD初学指南

    去年就打算总结一下,结果新换的工作特别忙,就迟迟没有认真动手.主要内容是很多初学DDD甚至于学习很长时间的同学没有弄明白DDD是什么,适合什么情况.这世界上没有银弹,抛开了适合的场景孤立的去研究DDD ...

  4. gulp初学

    原文地址:gulp初学 至于gulp与grunt的区别,用过的人都略知一二,总的来说就是2点: 1.gulp的gulpfile.js  配置简单而且更容易阅读和维护.之所以如此,是因为它们的工作方式不 ...

  5. 初学seaJs模块化开发,利用grunt打包,减少http请求

    原文地址:初学seaJs模块化开发,利用grunt打包,减少http请求 未压缩合并的演示地址:demo2 学习seaJs的模块化开发,适合对seajs基础有所了解的同学看,目录结构 js — —di ...

  6. JavaWeb——Listener

    一.基本概念 JavaWeb里面的listener是通过观察者设计模式进行实现的.对于观察者模式,这里不做过多介绍,大概讲一下什么意思. 观察者模式又叫发布订阅模式或者监听器模式.在该模式中有两个角色 ...

  7. 严重: Exception sending context initialized event to listener instance of class

    问题描述:Exception sending context initialized event to listener instance of class org.springframework.w ...

  8. [转]ExtJS学习笔记(二):handler与listener的区别

    原文地址:http://blog.csdn.net/smilingleo/article/details/3733177 ExtJS里handler和listener都是用来对用户的某些输入进行处理的 ...

  9. 初学Vue2.0--基础篇

    概述: 鉴于本人初学,使用的编译器是webStorm,需添加对VUE的支持,添加方法可以参考 http://www.jianshu.com/p/142dae4f8b51. 起步: 1. 扎实的 Jav ...

随机推荐

  1. springmvc+jsp 拦截器下如何设置欢迎页面

    0.需求 如何让用户在浏览器地址栏键入[http://XXX.XXX.XX.XX:端口号/应用名/]以后自动跳转到系统的登录界面 1.web.xml 1.1 注意welcome-file-list的配 ...

  2. 使用springmvc,jsp,结合网页文本编辑器kindEditor实现基本博客编辑功能

    kindEditor官网:http://kindeditor.net/demo.php 个人实践: 为了在自己的项目中引入一个类似用户写博客的功能,在网上找到了kindeditor,真心又好又易用. ...

  3. git branch 命令

    1.git init 该命令执行之后并没有创建branch 2.git add 添加文件,这时branch 也还没生成.git branch name也没用 3.git commit 提交到git r ...

  4. SpringMVC------maven编译报错:Dynamic Web Module 3.0 requires Java 1.6 or newer

    如图所示: 但是 Eclipse 明明已经将编译级别设置为 1.7: 这是由于你的 Maven 编译级别是 jdk1.5 或以下,而你导入了 jdk1.6 以上的依赖包:查看 Eclipse 的 Na ...

  5. java.net.NoRouteToHostException:无法指定被请求的地址

    最近在做一个新项目的poc压测的时候发现了如下问题: TPS一直突破不了5000,按照计算理论上应该可以达到8000 tps/s左右的,查看数据库端口情况,吓一跳... netstat -ant | ...

  6. SpringMVC由浅入深day02_8json数据交互

    8 json数据交互 8.1 为什么要进行json数据交互 json数据格式在接口调用中.html页面中较常用,json格式比较简单,解析还比较方便. 比如:webservice接口,传输json数据 ...

  7. 【AI】face_recognition

    1.pip install cmake 2.pip install boost 3.pip install dlib 4.pip install face_recognition

  8. Apache Kafka 1.0.0正式发布!

    千呼万唤始出来,经过7年的发展与完善,Apache Kafka 1.0.0正式发布!在笔者看来,比起1.0.0引入的新功能,此版本最大的意义在于标识Kafka各种组件功能的稳定性.不过我们还是来看下1 ...

  9. oracle非空不做更新

    update test set B=nvl(p1,B),C=nvl(p2,C),D=nvl(p3,D),E=nvl(p4,E) where A='good'

  10. 《利用Python 进行数据分析》 - 笔记(4)----json

    解决方案: 读写文本格式的数据: pandas 提供了一些用于将表格型数据读取为DataFrame对象的函数 pandas 中的解析函数 函数的选项可以划分为以下几个大类 索引:将一个或多个列当做返回 ...