Servlet的事件监听器

本文深入探讨了Servlet监听器的概念及其在监听ServletContext、HttpSession和ServletRequest对象上的创建和销毁事件,同时介绍了如何使用这些监听器进行在线人数统计。通过示例代码演示了具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

监听器就是一个实现特定接口的普通java程序,这个程序专门用于监听另一个java对象的方法调用或属性改变,当被监听对象发生上述事件后,监听器某个方法将立即被执行。

Servle监听器:

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

Servlet规范针对这三个对象上的操作,又把这多种类型的监听器划分为三种类型。
监听三个域对象创建和销毁的事件监听器
监听域对象中属性的增加和删除的事件监听器
监听绑定到HttpSession域中的某个对象的状态的事件监听器。

监听servletContext域对象创建和销毁:

ServletContextListener接口用于监听ServletContext对象的创建和销毁事件。
ServletContext对象被创建时,激发contextInitialized(ServletContextEventsce)方法
ServletContext对象被销毁时,激发contextDestroyed(ServletContextEventsce)方法。

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

1.ServletContextListener接口:

MyServletContextListener:


publicclassMyServletContextListenerimplementsServletContextListener{

publicvoidcontextDestroyed(ServletContextEventarg0){

System.out.println(arg0.getServletContext()+"被创建了");

}

publicvoidcontextInitialized(ServletContextEventarg0){

System.out.println(arg0.getServletContext()+"被销毁了");

}

}

web.xml

<listener>

<listener-class>cn.class3g.web.listener.MyServletContextListener

</listener-class>

</listener>

2.HttpSessionListener接口

MySessionListener

publicclassMyHttpSessionListenerimplementHttpSessionListener{

publicvoidsessionCreated(HttpSessionEventarg0){

System.out.println(arg0.getSource()+"被销毁了");

}

publicvoidsessionDestroyed(HttpSessionEventarg0){

System.out.println(arg0.getSource()+"被创建了");

}

}

3.ServletRequestListener接口

MyServletRequestListener

publicclassMyServletRequestListenerimplementsServletRequestListener{

publicvoidrequestDestroyed(ServletRequestEventarg0){

System.out.println("请求对象"+arg0.getSource()+"被销毁了");

}

publicvoidrequestInitialized(ServletRequestEventarg0){

System.out.println("请求对象"+arg0.getSource()+"被创建了");

}

}

统计当前在线人数:

OnlineListener

publicclassOnlineListenerimplementsHttpSessionListener{

publicvoidsessionCreated(HttpSessionEventarg0){

ServletContextcontext=arg0.getSession().getServletContext();

Integercount=(Integer)context.getAttribute("peopleOnline");

if(count==null){

count=1;

}else{

count++;

}

context.setAttribute("peopleOnline",count);

}

publicvoidsessionDestroyed(HttpSessionEventarg0){

ServletContextcontext=arg0.getSession().getServletContext();

Integercount=(Integer)context.getAttribute("peopleOnline");

count--;

context.setAttribute("peopleOnline",count);

}

}

web.xml:

<listener>

<listener-class>cn.class3g.web.listener.OnlineListener</listener-class>

</listener>

Index.jsp

<body>

统计当前在线人数为:${applicationScope.peopleOnline}

<%

System.out.println(application.getAttribute("peopleOnline"));

%>

</body>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值