1, 實現HttpSessionListener 接口 代碼如下
package com.whbester.portal.xj.web;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import com.whbester.portal.xj.bean.OnLineUserMap;
import com.whbester.portal.xj.db.DBUtils2;
public class MySessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
}
/**
* 當Session失效時,刪除在線用戶
*/
public void sessionDestroyed(HttpSessionEvent arg0) {
//得取Session
String sessionId = arg0.getSession().getId();
String userName = arg0.getSession().getAttribute("webusername")+"";
System.err.println("sessionId="+sessionId+" userName="+userName);
synchronized (this) {
if(userName != null && !"".equals(userName)){
//刪除靜態中的在線用戶
OnLineUserMap.remove(userName);
//刪除數據庫中的在線用戶
String sql = "delete from basic_users_online where user_code='"+userName+"'";
DBUtils2.executeUpdate(sql, null);
}
}
System.err.println("用戶退出"+userName);
}
}
2 在Web.xml中配置
<!-- 配置session -->
<listener>
<listener-class>
com.whbester.portal.xj.web.MySessionListener
</listener-class>
</listener>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!-- end 配置session -->
這樣就可以了
注:這樣在用戶非法退出後,可以在30分鐘後自動清除用戶