java监听服务_Java 监听器

监听器也叫Listener,是Servlet的监听器,它可以监听客户端的请求、服务端的操作等。通过监听器,可以自动激发一些操作,比如监听在线的用户的数量。

例:ServletContextListener监听ServletContext对象。

新建一个web项目

2873f4861b6587b2e0fb98f782eefb91.png

创建CountUtils和ListenerTest类并编写代码

271454eb089584eaf4fd8baba1378373.png

ae71124c95988d41f0d8fda65e82b95f.png

配置web.xml

b570c036f62e0f2d7d4caba4fe2866a5.png

编写jsp页面

e8403a7ef4c373458cfe3552960714c3.png

226a3fcdefea431a49717e03793c6b8f.png

运行代码并访问(两个人同时访问)

992bf83688d6be481e4d34e81e8a7da8.png

常用的监听接口:

ServletContextAttributeListener监听对ServletContext属性的操作,比如增加、删除、修改属性。

ServletContextListener监听ServletContext对象。

当创建ServletContext时,激发contextInitialized(ServletContextEvent   sce)方法;

当销毁ServletContext时,激发contextDestroyed(ServletContextEvent   sce)方法。

HttpSessionListener监听HttpSession的操作:

当创建一个Session时,激发sessionCreated(HttpSessionEvent   se)方法;

当销毁一个Session时,激发sessionDestroyed(HttpSessionEvent   se)方法。

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

当在Session增加一个属性时,激发attributeAdded(HttpSessionBindingEvent  se)方法;

当在Session删除一个属性时,激发attributeRemoved(HttpSessionBindingEvent   se)方法;

当在Session属性被重新设置时,激发attributeReplaced(HttpSessionBindingEvent   se)   方法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值