java中的监听器在哪里配置的_Java监听器Listener使用详解

在我的项目中有具体应用:https://github.com/ygj0930/CoupleSpace

监听器用于监听web应用中某些对象、信息的创建、销毁、增加,修改,删除等动作的发生,然后作出相应的响应处理。当范围对象的状态发生变化的时候,服务器自动调用监听器对象中的方法。常用于统计在线人数和在线用户,系统加载时进行信息初始化,统计网站的访问量等等。

分类:

按监听的对象划分,可以分为

ServletContext对象监听器

HttpSession对象监听器

ServletRequest对象监听器

按监听的事件划分

对象自身的创建和销毁的监听器

对象中属性的创建和消除的监听器

session中的某个对象的状态变化的监听器

示例:用监听器统计网站在线人数

原理:每当有一个访问连接到服务器时,服务器就会创建一个session来管理会话。那么我们就可以通过统计session的数量来获得当前在线人数。

所以这里用到的是HttpSessionListener。

1:创建监听器类,实现HttpSessionListener接口。

f5d54f57329271e13aed5d60ea7d2d65.png

2:重写监听器类中的方法

public class onLineCount implementsHttpSessionListener {public int count=0;//记录session的数量public voidsessionCreated(HttpSessionEvent arg0) {//监听session的创建

count++;

arg0.getSession().getServletContext().setAttribute("Count", count);

}

@Overridepublic voidsessionDestroyed(HttpSessionEvent arg0) {//监听session的撤销

count--;

arg0.getSession().getServletContext().setAttribute("Count", count);

}

}

3:在web.xml中配置监听器。注意:监听器>过滤器>serlvet,配置的时候要注意先后顺序

com.ygj.control.onLineCount

在Servlet3.0中,监听器的配置可以直接在代码中通过注释来完成,无需在web.xml中再配置。

@WebListener //在此注明以下类是监听器public class onLineCount implementsHttpSessionListener {public int count=0;public voidsessionCreated(HttpSessionEvent arg0) {

count++;

arg0.getSession().getServletContext().setAttribute("Count", count);

}

@Overridepublic voidsessionDestroyed(HttpSessionEvent arg0) {

count--;

arg0.getSession().getServletContext().setAttribute("Count", count);

}

4:在显示在线人数处通过session.getAttribute("Count")即可获取在线人数值。

附:常用监听器

除了上面监听session建立与销毁的listener外,还有以下几个常用的监听器。

1:监听session属性的增加、移除以及属性值改变的HttpSessionAttributeListener

f12f764abd1c2adb27e4bb12270248fa.png

2:监听web上下文的初始化(服务器已准备好接收请求)与销毁的ServletContextListener

e5a15db6c98d47f6f5fe772849c1736e.png

3:监听web上下文属性的增加、删除、属性值变化的ServletContextAttributeListener

65ceed45cec5ac111a5753f81fc39acf.png

4:监听request的创建与销毁的ServletRequestListener

4727a6c51dcbedddba57b8b49e9399b9.png

5:监听request的属性的增加、删除、属性值变化的ServletRequestAttributeListener

65b6d21034264168087065dfc5dfeac6.png

内容来源于网络如有侵权请私信删除

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值