转:Session 治理
原帖:http://hi.baidu.com/jlh_jianglihua/item/9007f429de1855ff51fd87a5
最近一个项目中用到了getsession根据sessionid来获取session,但是怎么获取都为空,请教N多人,才发现在servlet的api中有如下:
HttpSession HttpSessionContext.getSession(java.lang.String sessionId)
不赞成的用法. Java Servlet API的版本 2.1中,还没有将之替换掉。该方法必须返回一个空值,且将会在未来的版本中被抛弃掉。
最新的解决办法是通过实现HttpSessionListener的sessionCreated和sessionDestroyed来实现
解决步骤:
1、在web.xml增加监听:
<listener>
<listener-class>com.aceway.util.LoginSessionListener</listener-class>
</listener>
2、LoginSessionListener:
LoginSessionListener方法实现了HttpSessionListener,并且重写sessionCreated和sessionDestroyed方法
public static Map userMap = new HashMap(); //创建了一个对象来保存session的
private MySessionContext myc=MySessionContext.getInstance(); //MySessionContext是实现session的读取和删除增加 单例模式
public void sessionCreated(HttpSessionEvent event)
{
myc.AddSession(event.getSession());
}
public void sessionDestroyed(HttpSessionEvent event)
{
HttpSession session = event.getSession();
myc.DelSession(session);
}
3、session的单例管理
Java代码
package com.aceway.flex;
import java.util.*;
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);
}
}
4、这样我们就可以单例来获取session
private MySessionContext myc=MySessionContext.getInstance();
HttpSession session = myc.getSession(SessionId);