一. 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. Servlet3简介

    servlet基础知识:http://blog.csdn.net/chjttony/article/details/6086292 ServletContext相关知识:http://blog.csd ...

  2. dede栏目添加自定义字段方法

    1.首先要进mysql 数据库里添加字段,命名好!比如我下面添加了一个栏目备注字段,当然你字段可以自己新建,找到表dede_arctype(这个是栏目模型的数据库表,这里面我添加的是栏目备注字段cla ...

  3. ./configure、make、make install 命令

    https://www.cnblogs.com/tinywan/p/7230039.html https://www.sohu.com/a/191735643_505857 ./configure 该 ...

  4. JAVAWEB开发之Session的追踪创建和销毁、JSP具体解释(指令,标签,内置对象,动作即转发和包括)、JavaBean及内省技术以及EL表达式获取内容的使用

    Session的追踪技术 已知Session是利用cookie机制的server端技术.当client第一次訪问资源时 假设调用request.getSession() 就会在server端创建一个由 ...

  5. 5 -- Hibernate的基本用法 --4 7 二级缓存相关属性

    Hibernate的SessionFactory可持有一个可选的二级缓存,通过使用这种二级缓存可以提高Hibernate的持久化访问的性能. Hibernate的二级缓存属性: ⊙ hibernate ...

  6. SpringBoot application.properties (application.yml)优先级从高到低

    SpringBoot application.properties(application.yml) 优先级从高到低 SpringBoot配置文件优先级从高到低 =================== ...

  7. Apache 配置文件详解

    0x01 禁止目录列表访问 () 备份httpd.conf配置文件,修改内容: <Directory "/web"> Options FollowSymLinks Al ...

  8. NUC972裸机调试步骤

    .将开发板设置成USB启动.开发板拨码开关与启动方式设置对应如下: 其中PA1 ,PA0对应S1和S0 上电或复位,使开发板从USB启动.开启NuWriter,选择正确的芯片型号,按下“Continu ...

  9. 在css中 父元素不固定高度,怎样实现子元素的高度100%

    父元素使用 position: relative; 子元素使用 position: absolute; height: 100%;

  10. 《转载》Fiddler 抓包工具总结

    阅读目录 1. Fiddler 抓包简介 1). 字段说明 2). Statistics 请求的性能数据分析 3). Inspectors 查看数据内容 4). AutoResponder 允许拦截制 ...