如何根据sessionID获取session
2015-04-18 13:25
633 查看
根据sessionID有一个比较简单的方法,使用session上下文即可
不过很可惜,java之后处于安全性考虑,不建议使用这个方法,虽然我不知道为什么对安全性会有影响,但是既然java不建议用了,那我们怎么办,毕竟大牛多,下面来分享一个方法,使用session监听器配合一个静态的hashmap即可实现。
上代码
==============HLL的分割线==================
首先,创建自己的sessionContext
然后建立session监听,要实现HttpSessionListener接口
接着,在web.xml中配置session监听器
完事,大功告成,之后在代码中直接获取就OK了
OK,第一篇博客,就到这吧,收!!!!!!
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,第一篇博客,就到这吧,收!!!!!!
相关文章推荐
- Java根据sessionId获取Session对象
- Android 如何根据资源的名字获取其ID值
- Java根据sessionId获取Session对象
- 根据sessionId获取相应的session
- 根据sessionid获取session的被Servlet2.1抛弃getsession方法的解决方案
- 根据sessionid获取session的被Servlet2.1抛弃getsession方法的解决方案
- 根据sessionId获取session对象
- 如何根据(id)sender获取UIButton的信息
- Java根据sessionId获取Session对象
- Java根据Session Id获取Session对象(转)
- Java根据sessionId获取Session对象
- java如何根据list以及根节点id获取树形展示数据?
- 你们帮我看看如何在datalist里面使用session获取ID值代码改怎么写啊麻烦了
- js如何根据id获取标签内的值,以及如何通过id赋值
- 微擎框架内如何根据media_id获取到微信图片的路径
- 根据sessionid获取session的被Servlet2.1抛弃getsession方法的解决方案
- 根据sessionId获取Session对象
- spring boot实现session 同步共享及 根据sessionid 获取相应的session
- Java根据sessionId获取Session对象
- JavaWeb根据sessionId获取session对象