日期:2014-05-18 浏览次数:20622 次
package online.MyEclipse.outpackage.online; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class CountListener implements ServletContextListener,ServletContextAttributeListener,HttpSessionListener,HttpSessionAttributeListener { private ServletContext application = null ; private HttpSession session = null ; public void contextInitialized(ServletContextEvent sce) { //初始化一个application对象,即application就是一个 //以tomcat的一次启动为整个周期的ServletContext this.application=sce.getServletContext(); //设置一个列表属性online,用于保存在线用户名 this.application.setAttribute("online", new ArrayList()); } public void contextDestroyed(ServletContextEvent sce) {} public void attributeAdded(ServletContextAttributeEvent scab) {} public void attributeRemoved(ServletContextAttributeEvent scab) {} public void attributeReplaced(ServletContextAttributeEvent scab) {} public void sessionCreated(HttpSessionEvent se) {} public void sessionDestroyed(HttpSessionEvent se) { //取得用户名列表 List online=(List)this.application.getAttribute("online") ; //取得当前用户名 String username=(String)se.getSession().getAttribute("name") ; //将此用户名从列表中删除 online.remove(username) ; //将删除后的列表重新设置到application属性中 this.application.setAttribute("online", online) ; } //当session增加一个属性时,激发attributeAdded(HttpSessionBindingEvent se) 方法 public void attributeAdded(HttpSessionBindingEvent se) { //取得用户名列表 List online=(List)this.application.getAttribute("online") ; //将当前用户名添加到列表中.list数组添加值的方式 list.add(); online.add(se.getValue()) ; //若是多维数组则调用相对应的属性的时候se.getValue("name"); //将添加后的列表重新设置到application属性中 this.application.setAttribute("online", online) ; } public void attributeRemoved(HttpSessionBindingEvent se) {} public void attributeReplaced(HttpSessionBindingEvent se) {} }
<%@ page contentType="text/html;charset=GB2312"%> <%@ page import="java.util.*"%> <html> <head> <title>sessionlistener</title> </head> <body> <form action="sessionlistener.jsp" method="post"> 用户名: <input type="text" name="username" /> <input type="submit" value="登录" /> <a href="logout.jsp">注销</a> </form> <% String username = request.getParameter("username"); if (username != null) { session.setAttribute("name", username); } %> <p> <h3> 在线用户: </h3> <hr> <% List online = (List) getServletContext().getAttribute("online"); Iterator iter = online.iterator(); while (iter.hasNext()) { %> <li> <%=iter.next()%> </li> <% } %> </body> </html>
<%@ page contentType="text/html;charset=GB2312" %> <html> <head> <title>logout</title> </head> <body> <