使用sessionID 获取session对象

1.建立session的监听

2.创建自己的sessionContext  目的是加一个session的集合

3.session的创建和销毁 修改sessioncodetext内的session的集合




1、sessioncontext创建

import java.util.HashMap;


import javax.servlet.http.HttpSession;


public class MySessionContext {     
    private static MySessionContext instance;     
    private HashMap mymap;     
         
    private MySessionContext() {     
        mymap = new HashMap();     
    }     
         
    public static MySessionContext getInstance() {     
        if (instance == null) {     
            instance = new MySessionContext();     
        }     
        return instance;     
    }     
         
    public synchronized void AddSession(HttpSession session) {     
        if (session != null) {     
            mymap.put(session.getId(), session);     
        }     
    }     
         
    public synchronized void DelSession(HttpSession session) {     
        if (session != null) {     
            mymap.remove(session.getId());     
        }     
    }     
         
    public synchronized HttpSession getSession(String session_id) {     
        if (session_id == null) return null;     
        return (HttpSession) mymap.get(session_id);     
    }     
     
}     


 

2.sessioncontext在session监听中



import java.util.List;


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


import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;



public class SessionListener implements HttpSessionListener {

private         MySessionContext myc=MySessionContext.getInstance();  
public void sessionCreated(HttpSessionEvent se) {
// TODO session创建
myc.AddSession(se.getSession());     

}


public void sessionDestroyed(HttpSessionEvent event) {
// TODOsession销毁
HttpSession ses = event.getSession();

       myc.DelSession(ses);  


 
}


}


 

3.调用

 

MySessionContext myc= MySessionContext.getInstance();     
HttpSession sess = myc.getSession(session的id]);  



已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页