用session监听器统计在线人数和在线人列表

1.SessionListenen.java

package listener; import java.util.Hashtable; import java.util.Iterator; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class SessionListener implements HttpSessionListener { // 创建集合保存session对象 private static Hashtable sessionList = new Hashtable(); // session创建触发的方法 public void sessionCreated(HttpSessionEvent event) { sessionList.put(event.getSession().getId(), event.getSession()); } // session过期或者销毁触发的方法 public void sessionDestroyed(HttpSessionEvent event) { sessionList.remove(event.getSession().getId()); } // 返回全部session对象集合 static public Iterator getSet() { return sessionList.values().iterator(); } // 根据session对象的id返回session对象 static public HttpSession getSession(String sessionId) { return (HttpSession) sessionList.get(sessionId); } } 

2.LoginAction.java

package action; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import listener.SessionListener; import model.User; import service.UserService; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport { private User user; private String message; private UserService service; public String execute() throws Exception { Map session = ActionContext.getContext().getSession(); boolean flag = false;// 标志用户是否已经登录 user=service.checkLogin(user); if (user!=null) { int count = 0; List<User> userList = new ArrayList<User>(); Iterator iterator = SessionListener.getSet(); while (iterator.hasNext()) { // 得到每个session HttpSession se = (HttpSession) iterator.next(); User u = (User) se.getAttribute("user"); if (u != null) { userList.add(u); count++; //如果当前的登录的用户session中已经有该用户的Id了,则将flag置为true if (user.getId()==(u.getId())) { flag = true; } } } // 如果用户没有登录 if (!flag) { session.put("user", user); userList.add(user); count++; session.put("userList", userList); session.put("count", count); setMessage("哈哈,登录成功!" + "在线人数是:" + count); return SUCCESS; } else { setMessage("您已经在线了!"); return ERROR; } } else { setMessage("用户密码错误!"); return ERROR; } } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public UserService getService() { return service; } public void setService(UserService service) { this.service = service; } }  

可以去http://download.csdn.net/source/3123435下载源码

你可能感兴趣的:(用session监听器统计在线人数和在线人列表)