在login后,向session中加入userBean
request.getSession().setAttribute("userBean", userBean);
1.web.xml
<!-- 加载session监听 -->
<listener>
<listener-class>com.free.common.MySessionListener</listener-class>
</listener>
2.MySessionListener.java
package com.free.common;
import java.util.*;
import java.util.Map.*;
import javax.servlet.http.*;
import com.free.pojo.*;
public class MySessionListener implements HttpSessionListener, HttpSessionAttributeListener{
// 保存sessionID和userBean的映射 key-sessionId
private static Map<String, TUser> userMap = new HashMap<String, TUser>();
private static Map<String, HttpSession> sessionMap = new HashMap<String, HttpSession>();
public MySessionListener(){
}
/** 以下是实现HttpSessionListener中的方法 **/
public void sessionCreated(HttpSessionEvent se) {
}
public void sessionDestroyed(HttpSessionEvent se) {
String sessionId = se.getSession().getId();
TUser userBean = (TUser) se.getSession().getAttribute(Common.CONSTANT_USER);
if(null == userBean){
return;
}
String username = userBean.getUsername();
userMap.remove(username);
sessionMap.remove(sessionId);
}
/** 以下是实现HttpSessionAttributeListener中的方法 **/
public void attributeAdded(HttpSessionBindingEvent se) {
if(Common.CONSTANT_USER.equals(se.getName())) {
TUser userBean = (TUser) se.getSession().getAttribute(Common.CONSTANT_USER);
String sessionId = se.getSession().getId();
String username = userBean.getUsername();
userBean.setSessionId(sessionId);
/**
* 踢掉已经存在的用户
*/
TUser ub1 = userMap.get(username);// 已经存在的用户
if(null != ub1 && ub1.getUsername().equals(userBean.getUsername())){
singleLogin(ub1.getId());
}
userMap.put(username, userBean);
sessionMap.put(sessionId, se.getSession());
}
}
public void attributeRemoved(HttpSessionBindingEvent se) {
}
public void attributeReplaced(HttpSessionBindingEvent se) {
}
/**
* 描述:singleLogin 单点登录-踢掉之前的用户
* @CreateOn Jul 26, 2011 9:20:04 PM
* @author chun_chang
*/
public static void singleLogin(String userId) {
clearUserById(userId);
}
/**
* 描述:clearUserById 清空同一在线用户的session
* @param userId
* @CreateOn Jul 25, 2011 11:05:44 AM
* @author chun_chang
*/
public static void clearUserById(String userId) {
Map<String, TUser> tempMap = new HashMap<String, TUser>();
tempMap.putAll(userMap);
Iterator<Entry<String, TUser>> iter = tempMap.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry<String, TUser> entry = (Map.Entry<String, TUser>) iter.next();
TUser userBean = entry.getValue();
if(userId.equals(userBean.getId())) {
String sessionId = userBean.getSessionId();
HttpSession session = sessionMap.get(sessionId);
session.removeAttribute(Common.CONSTANT_USER);
session.invalidate();
sessionMap.remove(sessionId);
}
}
}
}