servletlistener种类_Servlet之监听器(Listener)

一、监听器(Listener)概述

1、概念

JavaWeb中的监听器是Servlet规范中定义的一种特殊类,它用于监听web应用程序中的ServletContext, HttpSession和 ServletRequest等域对象的创建与销毁事件,以及监听这些域对象中的属性发生修改的事件,并自动根据不同情况,在后台调用相应的处理程序。

通过监听器,可以自动激发一些操作,比如监听在线人数,当增加一个HttpSession时就激发 sessionCreated(HttpSessionEvent)方法,这样就可以给在线人数加1。

2、监听器类型

在Servlet规范中定义了多种类型的监听器,它们用于监听的事件源分别为 ServletContext, HttpSession 和 ServletRequest 这三个域对象。

Servlet规范针对这三个对象上的操作,又把这多种类型的监听器划分为三种类型。

1. 监听三个域对象创建和销毁的事件监听器

2. 监听域对象中属性的增加和删除的事件监听器

3. 监听绑定到 HttpSession 域中的某个对象的状态的事件监听器

二、监听三个域对象创建和销毁的事件监听器

1.ServletContext域对象

编写一个ServletContextListener_test类,实现ServletContextListener接口,监听ServletContext对象的创建和销毁

1 packagecom.yx.servlet.listener;2

3 importjavax.servlet.ServletContextEvent;4 importjavax.servlet.ServletContextListener;5 importjavax.servlet.annotation.WebListener;6

7 /**

8 * Application Lifecycle Listener implementation class ServletContextListener_test9 * @Description:ServletContextListener_test实现了ServletContextListener接口,10 * 因此可以对ServletContext对象的创建和销毁两个动作进行监听11 */

12 @WebListener13 public class ServletContextListener_test implementsServletContextListener {14 /**

15 * Default constructor.16 */

17 publicServletContextListener_test() {18

19 }20

21 /**

22 *@seeServletContextListener#contextInitialized(ServletContextEvent)23 */

24 public voidcontextInitialized(ServletContextEvent sce) {25 System.out.println("ServletContext对象创建");26 }27 /**

28 *@seeServletContextListener#contextDestroyed(ServletContextEvent)29 */

30 public voidcontextDestroyed(ServletContextEvent sce) {31 System.out.println("ServletContext对象销毁");32 }33 }

ServletContextEvent的主要方法:ServletContext getServletContext():取得当前的ServletContext对象

在web.xml中注册监听器:要想监听事件源,那么必须将监听器注册到事件源上才能够实现对事件源的行为动作进行监听。

com.yx.servlet.listener.ServletContextListener_test

2、HttpSession域对象

1 packagecom.yx.servlet.listener;2

3 importjavax.servlet.annotation.WebListener;4 importjavax.servlet.http.HttpSessionEvent;5 importjavax.servlet.http.HttpSessionListener;6

7 /**

8 * Application Lifecycle Listener implementation class HttpSeeionListener_test9 *10 * HttpSession的销毁时机需要在web.xml中进行配置11 */

12 @WebListener13 public class HttpSeeionListener_test implementsHttpSessionListener {14

15 /**

16 * Default constructor.17 */

18 publicHttpSeeionListener_test() {19 //TODO Auto-generated constructor stub

20 }21

22 /**

23 *@seeHttpSessionListener#sessionCreated(HttpSessionEvent)24 */

25 public voidsessionCreated(HttpSessionEvent hse) {26 System.out.println(hse.getSession()+"创建了");27 }28 /**

29 *@seeHttpSessionListener#sessionDestroyed(HttpSessionEvent)30 */

31 public voidsessionDestroyed(HttpSessionEvent hse) {32 System.out.println("session销毁了");33 }34

35 }

HttpSessionEvent的主要方法:HttpSession getSession()

在web.xml中注册监听器:

com.yx.servlet.listener.HttpSeeionListener_test

1

3.  ServletRequest域对象

1 public voidrequestInitialized(ServletRequestEvent sre) {2 System.out.println(sre.getServletRequest()+"创建");3 }4 /**

5 *@seeServletRequestListener#requestDestroyed(ServletRequestEvent)6 */

7 public voidrequestDestroyed(ServletRequestEvent sre) {8 System.out.println(sre.getServletRequest()+"销毁");9 }

ServletRequestEvent实例中的方法:getServletRequest():获取ServletRequest对象;

getServletContext():获取ServletContext对象。

com.yx.servlet.listener.ServletRequestListener_test

三、监听域对象中属性的变更的监听器

1.ServletContextAttributeListener

用于监听Web应用属性改变的事件,包括增加、删除、修改属性。监听器类需要实现ServletContextAttributeListener接口。

ServletContextAttributeListener接口的主要方法:

(1)void attributeAdded(ServletContextAttributeEvent se):若有对象加入Application的范围,通知正在收听的对象。

(2)void attributeRemoved(ServletContextAttributeEvent se):若有对象从Application范围移除,通知正在收听的对象。

(3)void attributeReplaced(ServletContextAttributeEvent se):若在Application的范围中,有对象取代另一个对象时,通知正在收听的对象

ServletContextAttributeEvent中的主要方法:

getName():返回属性名称

getValue():返回属性的值

2.HttpSessionAttributeListener:监听HttpSession中属性的操作

该接口的主要方法:

(1)void attributeAdded(HttpSessionBindingEvent se):监听Http会话中的属性添加

(2)void attributeRemoved(HttpSessionBindingEvent se):监听Http会话中的属性移除

(3)void attributeReplaced(HttpSessionBindingEvent se):监听Http会话中的属性更改操作

3. ServletRequestAttributeListener:用于监听Web应用属性改变的事件,包括增加属性、删除属性、修改属性

接口方法:

(1)void attributeAdded(ServletRequestAttributeEvent e):向Request对象添加新属性

(2)void attributeRemoved(ServletRequestAttributeEvent e):从request对象中删除属性

(3)void attributeReplaced(ServletRequestAttributeEvent e):替换对象中现有属性值

ServletRequestAttributeEvent中的主要方法:

getName():返回Request增加、删除、或替换的属性名称

getValue():返回Request增加、删除、或替换的属性的值

注:以上均需要在web.xml中进行配置

四、监听绑定到 HttpSession 域中的某个对象的状态的事件监听器

1.HttpSessionBindingListener接口

注意:HttpSessionBindingListener接口是唯一不需要再web.xml中设定的Listener

当我们的类实现了HttpSessionBindingListener接口后,只要对象加入Session范围(即调用HttpSession对象的setAttribute方法的时候)或从Session范围中移出

(即调用HttpSession对象的removeAttribute方法的时候或SessionTime out的时候)时,可以感知自己何时被绑/解绑HttpSession域中,容器分别会自动调用下列两个方法:

void valueBound(HttpSessionBindingEvent event)

void valueUnbound(HttpSessionBindingEvent event)

2.HttpSessionActivationListener接口:监听Http会话的active和passivate状态。接口中定义的回调方法有:

session对象被保存到磁盘时,激发 sessionWillPassivate(HttpSessionEvent)

session对象被调入内存时,激发 sessionDidActivate(HttpSessionEvent)

Activate与Passivate是用于置换session对象的动作,当Web服务器因为资源利用或负载平衡等原因要将内存中的 session对象暂时储存至硬盘或其它储存器时(通过对象序列化),所作的动作称之为Passivate,而硬盘或储存器上的session对象重新加 载到JVM中时所采的动作称之为Activate。sessionDidActivate()方法与 sessionWillPassivate()方法分别于Activeate后与Passivate前被调用。

参考博文:

(1)http://www.cnblogs.com/xdp-gacl/p/3961929.html;http://www.cnblogs.com/xdp-gacl/p/3969249.html

(2)http://www.cnblogs.com/ymf123/p/5017622.html

(3)http://blog.csdn.net/rongxiang111/article/details/53487381

(4)http://blog.csdn.net/u011120983/article/details/50468407

(5)http://blog.csdn.net/xxssyyyyssxx/article/details/50007833

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以实现Jsp连接Mysql数据库的监听器。具体实现步骤如下: 1. 在web.xml文件中定义一个监听器: ``` <listener> <listener-class>com.xxx.xxx.MySqlListener</listener-class> </listener> ``` 2. 编写一个实现ServletContextListener接口的监听器MySqlListener,并在其中编写连接Mysql数据库的代码: ``` public class MySqlListener implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/databaseName"; String user = "username"; String password = "password"; Connection conn = null; try { Class.forName(driver); conn = DriverManager.getConnection(url, user, password); event.getServletContext().setAttribute("conn", conn); } catch (Exception e) { e.printStackTrace(); } } public void contextDestroyed(ServletContextEvent event) { Connection conn = (Connection) event.getServletContext().getAttribute("conn"); try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } ``` 3. 在Jsp页面中使用EL表达式获取ServletContext中的Connection对象,从而连接Mysql数据库: ``` <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <% Connection conn = (Connection) application.getAttribute("conn"); PreparedStatement ps = null; ResultSet rs = null; try { ps = conn.prepareStatement("SELECT * FROM tableName"); rs = ps.executeQuery(); while (rs.next()) { out.print(rs.getString("columnName") + "<br/>"); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (ps != null) ps.close(); } catch (SQLException e) { e.printStackTrace(); } } %> ``` 通过以上步骤,我们就可以在Jsp页面中连接Mysql数据库并执行SQL语句了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值