本文实例讲述了JSP监听器用法。分享给大家供大家参考,具体如下:
监听器也叫Listener,是servlet服务的监听器。它可以监听客户端的请求,服务端的操作等。比如统计在线用户数量。每当增加一个HttpSession时,就会触发sessionCreate(HttpSessionEvent se)方法,这样就可以给在线人数加1.常用的监听器接口如下:
1. ServletContextAttributeListener监听对ServletContext属性的操作。比如增加,删除,修改属性。
2. ServletContextListener监听ServletContext。当创建ServletContext时,激发contextInitialized(ServletContextEvent sce)方法;当销毁ServletContext时,激发contextDestroyed(ServletContextEvent sce)方法。
3. HttpSessionListener监听HttpSession的操作。当创建一个Session时,激发session Created(HttpSessionEvent se)方法;当销毁一个Session时,激发sessionDestroyed (HttpSessionEvent se)方法。
4. HttpSessionAttributeListener监听HttpSession中的属性的操作。当在Session增加一个属性时,激发attributeAdded(HttpSessionBindingEvent se) 方法;
当在Session删除一个属性时,激发attributeRemoved(HttpSessionBindingEvent se)方法;
当在Session属性被重新设置时,激发attributeReplaced(HttpSessionBindingEvent se) 方法。
一个在线统计的例子:
public class ONline implements ServletContextListener,HttpSessionListener,HttpSessionAttributeListener(){ private ServletContext application = null; public void contextInitialized(ServletContextEvent arg0) { //根据响应事件参数初始化ServletContext this.application = arg0.getServletContext(); //在ServletContext中存放一个空的用户信息列表 application.setAttribute("users", new ArrayList()); } public void sessionDestroyed(HttpSessionEvent arg0) { List list = (List)application.getAttribute("users"); String name = arg0.getSession().getAttribute("name").toString(); list.remove(name); application.setAttribute("users", list); } public void attributeAdded(HttpSessionBindingEvent arg0) { List list = (List)application.getAttribute("users"); if(arg0.getName().equals("name")){ list.add(arg0.getValue().toString()); } application.setAttribute("users", list); } }
web.xml文件中配置:
<listener> <listener-class>package.classname</listener-class> </listener>
附:session在何时被创建"false"%>来关闭session,则在jsp页面编译成Servlet页面时会自动加上HttpServletRequest.getSession(true)这句话。这也是jsp中隐藏对象session的来历。
希望本文所述对大家jsp程序设计有所帮助。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 贵族音乐《古典名曲与轻音乐钢琴 打开宝宝睡眠开关》[FLAC/分轨][251.78MB]
- 黄韵玲2001-巴结音乐[全员集合][WAV+CUE]
- 郑绪岚2015-流金岁月·精选[首版][WAV+CUE]
- 周冰倩1995《沧桑情歌》JVC日本录制[WAV+CUE]
- 辛禄乐队.2024-热烈的少年【星辰】【FLAC分轨】
- 成龙.1996-龙的心【滚石】【WAV+CUE】
- 童安格.1991-一世情缘【宝丽金】【WAV+CUE】
- 韩红2010-擦肩而过[央金玛][WAV+CUE]
- RiccardoTesi-UnballoLiscio,Vol.II(2024)[24-48]FLAC
- 金池VS刘罡2009《双声情》[WAV+CUE]
- 冯奥迪《卄》[320K/MP3][67.08MB]
- 冯奥迪《卄》[FLAC/分轨][172.46MB]
- Merryland《Merryland》[320K/MP3][69.48MB]
- 苏芮.1991-停在我心里的温柔【福茂】【WAV+CUE】
- 苏慧伦.2020-面面Every.Side.of.Me【相信音乐】【WAV+CUE】