初学Listener
一. Listener 介绍
Servlet API提供了大量监听器来监听web应用的的内部事件,从而允许当web内部事件发生时回调事件监听器内的方法。
使用listener分为两步
- 定义LIstener实现类
- 通过注解或在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的更多相关文章
- ORACLE清理、截断监听日志文件(listener.log)
在ORACLE数据库中,如果不对监听日志文件(listener.log)进行截断,那么监听日志文件(listener.log)会变得越来越大,想必不少人听说过关于"LISTENER.LOG日 ...
- 使用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 ...
- DDD初学指南
去年就打算总结一下,结果新换的工作特别忙,就迟迟没有认真动手.主要内容是很多初学DDD甚至于学习很长时间的同学没有弄明白DDD是什么,适合什么情况.这世界上没有银弹,抛开了适合的场景孤立的去研究DDD ...
- gulp初学
原文地址:gulp初学 至于gulp与grunt的区别,用过的人都略知一二,总的来说就是2点: 1.gulp的gulpfile.js 配置简单而且更容易阅读和维护.之所以如此,是因为它们的工作方式不 ...
- 初学seaJs模块化开发,利用grunt打包,减少http请求
原文地址:初学seaJs模块化开发,利用grunt打包,减少http请求 未压缩合并的演示地址:demo2 学习seaJs的模块化开发,适合对seajs基础有所了解的同学看,目录结构 js — —di ...
- JavaWeb——Listener
一.基本概念 JavaWeb里面的listener是通过观察者设计模式进行实现的.对于观察者模式,这里不做过多介绍,大概讲一下什么意思. 观察者模式又叫发布订阅模式或者监听器模式.在该模式中有两个角色 ...
- 严重: Exception sending context initialized event to listener instance of class
问题描述:Exception sending context initialized event to listener instance of class org.springframework.w ...
- [转]ExtJS学习笔记(二):handler与listener的区别
原文地址:http://blog.csdn.net/smilingleo/article/details/3733177 ExtJS里handler和listener都是用来对用户的某些输入进行处理的 ...
- 初学Vue2.0--基础篇
概述: 鉴于本人初学,使用的编译器是webStorm,需添加对VUE的支持,添加方法可以参考 http://www.jianshu.com/p/142dae4f8b51. 起步: 1. 扎实的 Jav ...
随机推荐
- 如何用一个for循环打印出一个二维数组
思路分析: 二维数组在内存中默认是按照行存储的,比如一个二维数组{{1,2,3,},{4,5,6}},它在内存中存储的顺序就是1.2.3.4.5.6,也就是说,对于这6个数组元素,按照从0到5给它们编 ...
- SpringBoot Cmd运行Jar文件指定active文件的命令如下
SpringBoot Cmd运行Jar文件指定active文件的命令如下 SpringBoot 命令行指定配置文件运行 ================================ ©Copyri ...
- Linux关闭Tomcat为什么要用Kill,而不是shutdown.sh
Linux关闭Tomcat为什么要用Kill,而不是shutdown.sh >>>>>>>>>>>>>>>&g ...
- Spring中神奇@aotuWrited
好久没有写博客了,放假就是充电学习的时候,的确一直是这样做的.来给自己一点掌声.我们还是进入今天的主题吧. 我们自己写代码一般会向下面这样干啊,因为这样简单,其余交给spring去做吧.Spring会 ...
- 【代码审计】CmsEasy_v5.7 代码执行漏洞分析
0x00 环境准备 CmsEasy官网:http://www.cmseasy.cn/ 网站源码版本:CmsEasy_v5.7_UTF8-0208 程序源码下载: http://ftp.cmseas ...
- 基于github+hexo搭建个人博客(window)
0x01 环境搭建 1.Node.js环境 下载Node.js安装文件:https://nodejs.org/en/download/ 根据系统选择相应安装包下载,安装过程一路Next,默认设置即可. ...
- vmware 安装 Mac OS X 10.9 Mavericks
This guide shows how to install fresh OS X 10.9 Mavericks on VMware workstation with Windows 7 or Wi ...
- Ansible的Inventory管理
Ansible将可管理的服务器集合成为Inventory,Inventory的管理便是服务器的管理. hosts文件的位置: /etc/ansible/hosts 在命令行通过-i参数指定 通过/et ...
- ASP.NET MVC入门到精通——数据库仓储
业务层调用数据层对象,我不想每次都new一个数据层对象,而是在数据层创建一个仓储,统一管理所有的对象调用. 1.在IDAL项目中,新建IDBSession.tt模板 Ctrl+S后自动生成IDBS ...
- [C] 如何使用头文件 .h 编译 C 源码
在 C 语言中,头文件或包含文件通常是一个源代码文件,程序员使用编译器指令将头文件包含进其他源文件的开始(或头部),由编译器在处理另一个源文件时自动包含进来. 一个头文件一般包含类.子程序.变量和其他 ...