web.xml: //注册
<listener> <listener-class>org.eleaf.qsls.server.ActiveUserListener</listener-class> </listener>
ActiveUserListener.java: package org.eleaf.qsls.server;
import java.util.*; import javax.servlet.http.*; import org.eleaf.qsls.bbs.*;
public class ActiveUserListener implements HttpSessionListener { private static int sessionCount = 0; private static Map sessionMaps = new HashMap(); //存放session的集合类
public void sessionCreated(HttpSessionEvent arg0) { HttpSession session = arg0.getSession(); String sessionId = session.getId(); System.out.println("Create a session:" + sessionId); sessionMaps.put(sessionId, session); sessionCount++; }
public void sessionDestroyed(HttpSessionEvent arg0) { sessionCount--; String sessionId = arg0.getSession().getId(); sessionMaps.remove(sessionId);//利用会话ID标示特定会话 System.out.println("Destroy a session:" + sessionId); } public static int getSessionCount() { return sessionCount; } public static Map getSessionMaps() { return sessionMaps; } }
chklogin.jsp:
String name = request.getParameter("name"); String password = request.getParameter("password"); if (name == null && password == null) { response.sendRedirect("default.jsp"); return; } Author author = new Author(); //一个拥有一系列field字段和getter,setter方法的类,代表每个会话用户,直接映射到数据表 author.setName(name); author.setPassword(password); Community community = new Community(); //代表社区类,封装一些全局操作。 int authorId = community.checkAuthor(author); //在数据库中检索登陆数据,如果匹配则返回用户ID,否则返回0 if (0 != authorId) { Author sessionAuthor = community.getAuthor(authorId); //重新查询数据库,返回当前用户所有信息。 session.setAttribute("AUTHOR_INFO", sessionAuthor); //将从数据库得到的用户信息存放入会话 %> <jsp:forward page="main.jsp" /> <% } else { out.println("登陆失败,请返回重试!<br><a href='default.jsp'>返回</a>"); }
main.jsp: //显示当前所有会话信息
<%@ page import=“org.eleaf.qsls.bbs.*,org.eleaf.qsls.server.*“> Map activeSessions = ActiveUserListener.getSessionMaps(); Collection sessionsCollection = activeSessions.values();//得到当前所有会话之集合 Iterator iterSessions = sessionsCollection.iterator(); for (;iterSessions.hasNext();) { HttpSession mySession = (HttpSession) iterSessions.next(); Author myAuthor = (Author) mySession.getAttribute("AUTHOR_INFO"); if (author == null) { continue; } String myName = myAuthor.getName(); %> <a href="#"><%=myName%></a> | <% }
分析:
关键在于保存在集合中的元素都只是对外部对象的引用。所以当外部对象的数据被人为改变以后,在集合内部也同样进行了自动更新。 
|