初学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 ...
随机推荐
- Hibernate session FlushMode的五种设置
http://www.2cto.com/kf/201207/141455.html Hibernate session FlushMode有五种属性:1.NEVEL:已经废弃了,被MANUAL取代了2 ...
- UVA 1232 - SKYLINE(线段树)
UVA 1232 - SKYLINE option=com_onlinejudge&Itemid=8&page=show_problem&category=502&pr ...
- css媒体查询移动优先和pc优先
移动优先,默认你是用手机浏览该网页的,当你用pc浏览时,就会以min-width进行递增式媒体查询 <!DOCTYPE html> <html lang="en" ...
- C++ mysql 乱码
C++读mysql数据库中的中文显示出来的是乱码 在连接到数据库后加上这么一句 mysql_query(pMYSQL, "SET NAMES GB2312"); 或者 mysql_ ...
- Data Guard 主备库角色转换
1. switchover操作 1.1 备库先关闭实时日志应用 standby>alter database recover managed standby database cancel; 1 ...
- kafka进程总是在启动一段时间后自动停止
解决办法: bin/kafka-server-start.sh -daemon ./config/server.properties 进行启动,到现在为止 kafka 还在正常运行.和不加 -daem ...
- 【代码审计】iZhanCMS_v2.1 后台任意文件删除漏洞分析
0x00 环境准备 iZhanCMS官网:http://www.izhancms.com 网站源码版本:爱站CMS(zend6.0) V2.1 程序源码下载:http://www.izhancms ...
- 安装.NET Framework 3.5
https://www.microsoft.com/zh-CN/download/details.aspx?id=22 https://docs.microsoft.com/zh-cn/dotnet/ ...
- 【译】Kafka学习之路
一直在思考写一些什么东西作为2017年开篇博客.突然看到一篇<Kafka学习之路>的博文,觉得十分应景,于是决定搬来这“他山之石”.虽然对于Kafka博客我一向坚持原创,不过这篇来自Con ...
- AngularJS的初步学习(1)
AngularJS 是一个Javascript框架.它可通过 <script> 标签添加到 HTML 页面.AngularJS 通过 指令 扩展了 HTML,且通过 表达式绑定数据到 HT ...