项目中实现的统计现在人数的例子

来源:互联网 发布:路径规划算法 编辑:程序博客网 时间:2024/06/02 04:18

一、在web.xml中配置过滤器:

    <listener>
        <listener-class>com.geo.dsp.webapp.listener.UserCounterListener</listener-class>
    </listener>


1、启动一个WEB项目的时候,WEB容器会去读取它的配置文件web.xml,读取<listener> 和<context-param>两个结点。 
2、紧急着,容创建一个ServletContext(servlet上下文),这个 web项目的所有部分都将共享这个上下文。 
3、容器将<context-param>转换为键值对,并交给 servletContext。 ---》容器的一些常量
4、容器创建<listener>中的类实例,创建监听器。  --》在应用启动前就完成

二、UserCounterListener此方法实现了ServletContextListener, HttpSessionAttributeListener这两个接口,监听器也叫Listener,是Servlet的监听器,它可以监听客户端的请求、服务端的操作等。通过监听器,可以自动激发一些操作,比如监听在线的用户的数量。当增加一个HttpSession时,就激发sessionCreated(HttpSessionEvent 

  se)方法,这样
就可以给在线人数加1。常用的监听接口有以下几个:
ServletContextAttributeListener监听对ServletContext属性的操作,比如增加、删除、修改属性。
ServletContextListener监听ServletContext。当创建ServletContext时,激发 contextInitialized(ServletContextEvent   sce)方法;当销毁ServletContext时,激发contextDestroyed(ServletContextEvent   sce)方法。
HttpSessionListener监听HttpSession的操作。当创建一个Session时,激发session   Created(HttpSessionEvent   se)方法;当销毁一个Session时,激发sessionDestroyed   (HttpSessionEvent   se)方法。
HttpSessionAttributeListener监听HttpSession中的属性的操作。当在Session增加一个属性时,激发 attributeAdded(HttpSessionBindingEvent   se)   方法;当在Session删除一个属性时,激发attributeRemoved(HttpSessionBindingEvent   se)方法;当在Session属性被重新设置时,激发attributeReplaced(HttpSessionBindingEvent   se)   方法。



UserCounterListener设置全局变量USERS_KEY来保存登陆用户,页面读取

           <c:forEach items="${applicationScope.userNames}" var="user">
                      <tr align="center" onmouseover="this.style.background='#f7f9fb'" onmouseout="this.style.background=''" >
                        <td >&nbsp;${user.username}</td>
                        <td >&nbsp;${user.firstName} ${user.lastName}</td>
                     </tr>
           </c:forEach>

0 0