一. 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. 如何在Linux系统中安装VMware

    首先打开vmware官网的下载链接:https://my.vmware.com/web/vmware/info/slug/desktop_end_user_computing/vmware_works ...

  2. jsoup Cookbook(中文版)-Jsoup解析HTML

    jsoup Cookbook(中文版) 入门 1.      解析和遍历一个html文档 如何解析一个HTML文档: String html = "<html><head& ...

  3. .NET Framework 4.0源代码

    原文出处:http://blogs.microsoft.co.il/blogs/arik/archive/2010/07/12/step-into-net-framework-4-0-source-c ...

  4. ckeditor4.4.6添加代码高亮

    研究了很久才发现,在 ckeditor4.4.6中添加代码高亮超级简单啊,下面直接上过程 ckeditor4.4.6支持自定义代码高亮,利用Code Snippet插件并默认启用highlight.j ...

  5. 使用CountDownLatch模拟高并发场景

    import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java ...

  6. Jsoup(四)-- Jsoup获取DOM元素属性值

    1.获取博客园的博客标题以及博客地址,获取友情链接 2.代码实现: public static void main(String[] args) throws Exception{ // 创建http ...

  7. linux 下查看cpu信息

    linux 操作系统的位数查看 A. getconf LONG_BIT 如果是32表示是32位 B.  file /sbin/init信息全面一些 root@kali:~/software# file ...

  8. [Windows] Windows 8.x 取消触摸板切换界面

    在鼠标中选中UltraNav,找到Application Gestures - Edge Swipes,取消Enable Edge Swipes.

  9. [SublimeText] Sublime Text 2 在 Ubuntu 上安装指南

    1. 下载Sublime Text 2 在官网下载对应系统位数的版本,从压缩包中提取出源代码,解压后文件夹中的"sublime_text"双击即可直接运行. 2. 建立快捷链接 将 ...

  10. 细说php的异常和错误处理机制

    再谈php错误与异常处理 讲的非常好 w3school php异常处理机制 php错误异常处理详解 注: 关注set_error_handler() set_exception_handler() r ...