JSP监听器用法分析
Java  /  管理员 发布于 7年前   171
本文实例讲述了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在何时被创建?
常见的误解是session在有客户端访问时就被创建,然而事实是某server端调用HttpServletRequest.getSession(true)这样的语句时才被创建。注意如果jsp页面没有显式的使用<%page session="false"%>来关闭session,则在jsp页面编译成Servlet页面时会自动加上HttpServletRequest.getSession(true)这句话。这也是jsp中隐藏对象session的来历。
希望本文所述对大家jsp程序设计有所帮助。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号