今日搞了一个在线人员的一个小功能,利用javax.servlet.http.HttpSessionBindingListener接口对session进行监听,从而实现在创建session及删除session时及时对在线人员进行操作,在网上查看了一些资料,在的说建个表来记录,有些就不用建,至于建不建表进行记录,这完全看你个人的需求。下面贴出代码:
建一个类实现监听HttpSessionBindingListener接口
package com.webaorta.comm.util;
import java.util.Hashtable;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionBindingEvent;
import com.webaorta.comm.base.Logon;
public class MyHttpSessionBinding implements javax.servlet.http.HttpSessionBindingListener {
ServletContext application = null;
public MyHttpSessionBinding(){
}
public MyHttpSessionBinding(ServletContext application){
super();
if (application ==null) throw new IllegalArgumentException("Null application is not accept.");
this.application = application;
}
/*创建session时会调用此监听方法*/
@Override
public void valueBound(HttpSessionBindingEvent e) {
Hashtable activeSessions = (Hashtable) application.getAttribute("activeSessions");
if (activeSessions == null){
activeSessions = new Hashtable();
}
Logon sessionUser = (Logon)e.getSession().getAttribute("logon");
if (sessionUser != null){
activeSessions.put(e.getSession().getId(),sessionUser);//将sessionUser放置在hashtable里
System.out.println("在线人员: "+ sessionUser.getAccount());
}
application.setAttribute("activeSessions",activeSessions);
}
/*删除session时会调用此监听方法*/
@Override
public void valueUnbound(HttpSessionBindingEvent e) {
Logon sessionUser =(Logon)e.getSession().getAttribute("Logon");
if (sessionUser == null){
Hashtable activeSessions = (Hashtable) application.getAttribute("activeSessions");
if (activeSessions != null){
if(activeSessions.containsKey(e.getSession().getId())){
Logon logon = (Logon)activeSessions.get(e.getSession().getId());
System.out.println("离线人员: "+ logon.getUserId());
activeSessions.remove(e.getSession().getId());
application.setAttribute("activeSessions",activeSessions);
}
}
}
}
}
新建session时会调用valueBound方法,在删除或session过期时会调用valueUnbound方法,此时只需要在action里或jsp里的登录方法及退出方法里分别将session加入到监听类里则可以自动调用以上的那两个方法。代码如下:
//在检查数据库存在该用户后就可以将一些用户信息放入session中
private void checkuserLongo(){
...........
boolean isok = service.checkUser(name,pwd);
if(isok){
HttpSession session = request.getSession();
Logon logon = new Logon();
TUsers user = (TUsers)list.get(0);
logon.setUserId(newUserData.getId());
logon.setAccount(newUserData.getAccount());
logon.setPowerGroupId(newUserData.getTPowergroup().getId());
session.setAttribute("logon", logon);
//将监听类加入到session中才能对该session进行监听
session.setAttribute("bindingSession",new MyHttpSessionBinding(this.getServletContext()));
}
.........
}
//退出方法
private void logonOut(){
.....
HttpSession session = request.getSession(true);
if(!session.isNew()){
session.removeAttribute("logon");
session.removeAttribute("bindingSession");
}
session.invalidate();
.........
}