package my.util;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import my.web.actions.base.ApplicationContext;
import my.web.actions.base.Operator;
/**
* 在线用户监听器
*
*
* 2012-12-13 下午3:44:35
*/
public class OnlineUsersListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
// TODO Auto-generated method stub
System.out.println("创建session");
}
public void sessionDestroyed(HttpSessionEvent event) {
// TODO Auto-generated method stub
HttpSession session = event.getSession();
ServletContext application = session.getServletContext();
ApplicationContext context = (ApplicationContext) session.getAttribute(ApplicationContext.CONTEXT_NAME);
Long currentUserId = null;
if(context!=null&&context.getOperator()!=null){
//System.out.println(context.getOperator().getName()+"退出系统");
currentUserId = context.getOperator().getId();
}
List<Operator> onlineUsers = (List<Operator>) application.getAttribute(Constant.ONLINE_USERS);
if(onlineUsers!=null){
Iterator<Operator> it = onlineUsers.iterator();
while(it.hasNext()){
Operator o = it.next();
if(o.getId().equals(currentUserId)){
onlineUsers.remove(o);
break;
}
}
application.setAttribute(Constant.ONLINE_USERS,onlineUsers);
}
}
}
实体类
package my.web.actions.base;
import my.models.business.common.User;
/**
* 定义一个类、属性为操作者对象、作为应用上下文对象类
*
*
* @time 2012-7-22下午03:38:32
*/
public final class ApplicationContext {
public static final String CONTEXT_NAME = "applicaionContext";
private Operator operator;
private User user;
public Operator getOperator() {
return operator;
}
}
package my.web.actions.base;
import my.models.business.common.User;
/**
* 记录操作者信息的类
*
*
* @time 2012-6-28下午2:24:33
*
*/
public final class Operator {
private Long id;
private String name;
private String password;
private String realName;
private String language;
private String personalHome;
private String operatorStatus;//在线或离线
public Operator() {
}
public Operator(User user) {
if (null != user) {
this.id = user.getId();
this.name = user.getName();
this.password = user.getPassword();
this.realName = user.getRealName();
this.language = user.getLanguage();
this.personalHome = user.getPersonalHome();
} else {
this.id = 0l;
}
}
}
附:http://blog.sina.com.cn/s/blog_6218ee540100fian.html