您的位置:首页 > 其它

根据sessionid获取session的被Servlet2.1抛弃getsession方法的解决方案

2011-03-02 14:20 741 查看
最近一个项目中用到了getsession根据sessionid来获取session,但是怎么获取都为空,请教N多人,才发现在servlet的api中有如下:

HttpSession
HttpSessionContext.getSession(java.lang.String sessionId)


不赞成的用法. Java Servlet API的版本 2.1中,还没有将之替换掉。该方法必须返回一个空值,且将会在未来的版本中被抛弃掉。

最新的解决办法是通过实现HttpSessionListener的sessionCreated和sessionDestroyed来实现

解决步骤:

1、LoginSessionListener:

LoginSessionListener方法实现了HttpSessionListener,并且重写sessionCreated和sessionDestroyed方法

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class LoginSessionListener implements HttpSessionListener {
// MySessionContext是实现session的读取和删除增加单例模式
private MySessionContext myc = MySessionContext.getInstance();
public void sessionCreated(HttpSessionEvent event) {
myc.AddSession(event.getSession());
}
public void sessionDestroyed(HttpSessionEvent event) {
HttpSession session = event.getSession();
myc.DelSession(session);
}
}


web.xml中自动添加:

<listener>
<listener-class>com.ejitec.util.LoginSessionListener</listener-class>
</listener>


2、session的单例管理

@SuppressWarnings({ "rawtypes", "unchecked" })
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);
}
}


3、这样我们就可以单例来获取session

String sessionId = req.getParameter("jsessionid");
MySessionContext context = MySessionContext.getInstance();
HttpSession session = context.getSession(sessionId);


参考URL:http://laolang.cn/back-end-develop/getsessionjava-servlet-api.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: