public class SessionListener implements HttpSessionListener {
private static ArrayList<User> userlist = UserList.getUserlist();
private static User user=null;
public void sessionCreated(HttpSessionEvent arg0) {
String sessionId = arg0.getSession().getId();
if (userlist != null) {
for (int i = 0; i < userlist.size(); i++) {
User u = userlist.get(i);
if (u.getSessionIdByString() == sessionId) {
return;
}
}
}
user = new User();
user.setSessionIdByString(sessionId);
userlist.add(user);
arg0.getSession().getServletContext().setAttribute("user", userlist);
}
public void sessionDestroyed(HttpSessionEvent arg0) {
userlist.remove(user);
arg0.getSession().getServletContext().setAttribute("user", userlist);
}
}
public class User { private String sessionIdByString=""; public String getSessionIdByString() { return sessionIdByString; } public void setSessionIdByString(String sessionIdByString) { this.sessionIdByString = sessionIdByString; } }
package moedl;
import java.util.ArrayList;
public class UserList {
private static ArrayList<User> userlist = new ArrayList<User>();
public static ArrayList<User> getUserlist() {
return userlist;
}
// public static void setUserlist(ArrayList<User> userlist) {
// UserList.userlist = userlist;
// }
}
requestListener的实现是更进一步功能的实现。不仅可以看到在线用户,还可以看到在线用户的相关信息,比如定义中的IP
为了获取ip地址