session 监听

1.创建一个session容器用来存放所有的用户,不同浏览器对应不用的session,下面用单例模式来创建session容器

package com.limin.framework.util;

import java.util.HashMap;

import javax.servlet.http.HttpSession;

import com.limin.framework.listener.SessionListener;
import com.limin.util.Util;
/**
 * 使用单例模式
 */
public class SessionContext {
	private static SessionContext instance;  
    private HashMap<String,HttpSession> sessionMap;  
   
    private SessionContext() {  
        sessionMap = new HashMap<String,HttpSession>();  
    }  
  
    public static SessionContext getInstance() {  
        if (instance == null) {  
            instance = new SessionContext();  
        }  
        return instance;  
    }  
  
    public synchronized void AddSession(HttpSession session) {  
        if (session != null) {  
        	String userId = session.getAttribute("userId").toString();
        	if(Util.isNotNullorEmpty(userId)){
        	  sessionMap.put(userId,session);
        	}
        }  
    }  
  
    public synchronized void DelSession(HttpSession session) {  
        if (session != null) {  
        	String userId = session.getAttribute("userId").toString();
        	if(Util.isNotNullorEmpty(userId)){
        		sessionMap.remove(userId);
        	}
            session.invalidate(); 
        }  
    }  
  
    public HashMap<String,HttpSession> getSessionMap() {  
        return sessionMap;  
    }  
  
    public void setMymap(HashMap<String,HttpSession> sessionMap) {  
        this.sessionMap = sessionMap;  
    }  
    
    public static synchronized void sessionHandlerByCacheMap(HttpSession session){
    	try {
    		String userId = session.getAttribute("userId").toString();
    		HttpSession userSession=(HttpSession)SessionListener.sessionContext.getSessionMap().get(userId);
    		if(userSession!=null){  
    			//注销在线用户  
    			userSession.invalidate();
    		}
    		//清除在线用户后,更新map,替换map sessionid  对应session更换成新的session 
    		SessionListener.sessionContext.getSessionMap().put(userId,session);  
    	} catch (Exception e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}    
    } 
}

  2. 需要实现 HttpSessionListener 接口,创建一个 SessionListener

package com.limin.framework.listener;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.limin.framework.util.SessionContext;

public class SessionListener implements HttpSessionListener{
	public  static SessionContext sessionContext=SessionContext.getInstance();  
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {  
        sessionContext.AddSession(httpSessionEvent.getSession());  
    }  
  
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {  
        sessionContext.DelSession(httpSessionEvent.getSession());  
    }  
}

  

posted @ 2017-11-22 09:30  苦海无涯、苦尽甘来  阅读(939)  评论(0编辑  收藏  举报