监听器在线用户列表

时间:2022-11-18 22:43:20

index.jsp

在线用户列表:<br>
<%
List
<User> userList = (List<User>)application.getAttribute("userList");
if(userList!=null) {
for(User u : userList) {
out.print(u
+"<br>");
}
}
%>

User.java

import java.text.SimpleDateFormat;
import java.util.Date;

public class User {
private String sessionid;
private Date firstTime;

public String getSessionid() {
return sessionid;
}

public void setSessionid(String sessionid) {
this.sessionid = sessionid;
}

public Date getFirstTime() {
return firstTime;
}

public void setFirstTime(Date firstTime) {
this.firstTime = firstTime;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result
= prime * result + ((firstTime == null) ? 0 : firstTime.hashCode());
result
= prime * result + ((sessionid == null) ? 0 : sessionid.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other
= (User) obj;
if (firstTime == null) {
if (other.firstTime != null)
return false;
}
else if (!firstTime.equals(other.firstTime))
return false;
if (sessionid == null) {
if (other.sessionid != null)
return false;
}
else if (!sessionid.equals(other.sessionid))
return false;
return true;
}

@Override
public String toString() {
return "User [sessionid=" + sessionid + ", 最近登录时间="
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(firstTime) + "]";
}

}

 

TestSessionlistener.java

public void sessionCreated(HttpSessionEvent sessionEvent) {
userCount
++;
if(userList==null) {
userList
= new ArrayList<User>();
}
HttpSession session
= sessionEvent.getSession();

String sessionid
= session.getId();
long stime = session.getCreationTime();

if(!checkUsersSession(sessionid, userList)) {
User u
= new User();
u.setFirstTime(
new Date(stime));
u.setSessionid(sessionid);
userList.add(u);
}

session.getServletContext().setAttribute(
"userCount", userCount);
session.getServletContext().setAttribute(
"userList", userList);
}

private boolean checkUsersSession(String sessionid, ArrayList<User> userList2) {
for(User u : userList2) {
if(u.getSessionid().equals(sessionid)) {
return true;
}
}
return false;
}

/**
*
@see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
*/
public void sessionDestroyed(HttpSessionEvent sessionEvent) {
userCount
--;
HttpSession session
= sessionEvent.getSession();

String sessionid
= session.getId();
System.out.println(sessionid
+ "的用户下线");

if(checkUsersSession(sessionid, userList)) {
// for(User u : userList) {
// if(sessionid.equals(u.getSessionid())) {
// userList.remove(u);
// }
// }
Iterator<User> iter = userList.iterator();
while(iter.hasNext()) {
User u
= iter.next();
if(u.getSessionid().equals(sessionid)) {
iter.remove();
}
}
}
session.getServletContext().setAttribute(
"userCount", userCount);
session.getServletContext().setAttribute(
"userList", userList);
}

}