用Collection和HttpSessionListener获取当前所有会话信息

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

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> |

<%

}

分析:

关键在于保存在集合中的元素都只是对外部对象的引用。所以当外部对象的数据被人为改变以后,在集合内部也同样进行了自动更新。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航