您的位置:首页 > 其它

如何根据sessionID获取session

2015-04-18 13:25 633 查看
根据sessionID有一个比较简单的方法,使用session上下文即可

HttpSession sess = session.getSessionContext().getSession(sid)

不过很可惜,java之后处于安全性考虑,不建议使用这个方法,虽然我不知道为什么对安全性会有影响,但是既然java不建议用了,那我们怎么办,毕竟大牛多,下面来分享一个方法,使用session监听器配合一个静态的hashmap即可实现。

上代码

==============HLL的分割线==================

首先,创建自己的sessionContext

public class MySessionContext {
private static MySessionContext instance;
private HashMap<String,HttpSession> sessionMap;

private MySessionContext() {
sessionMap = new HashMap<String,HttpSession>();
}

public static MySessionContext getInstance() {
if (instance == null) {
instance = new MySessionContext();
}
return instance;
}

public synchronized void addSession(HttpSession session) {
if (session != null) {
sessionMap.put(session.getId(), session);
}
}

public synchronized void delSession(HttpSession session) {
if (session != null) {
sessionMap.remove(session.getId());
}
}

public synchronized HttpSession getSession(String sessionID) {
if (sessionID == null) {
return null;
}
return sessionMap.get(sessionID);
}

}


然后建立session监听,要实现HttpSessionListener接口

public class SessionListener implements HttpSessionListener {

private MySessionContext myc = MySessionContext.getInstance();

public void sessionCreated(HttpSessionEvent httpSessionEvent) {
HttpSession session = httpSessionEvent.getSession();
myc.addSession(session);
}

public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
HttpSession session = httpSessionEvent.getSession();
myc.delSession(session);
}

}


接着,在web.xml中配置session监听器

<listener>
<listener-class>SessionListener</listener-class>
</listener>


完事,大功告成,之后在代码中直接获取就OK了

MySessionContext myc= MySessionContext.getInstance();
HttpSession sess = myc.getSession(sessionId);


OK,第一篇博客,就到这吧,收!!!!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  session sessionID