转载自:https://blog.csdn.net/dennis19910627/article/details/45112615?locationNum=1&fps=1
根据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,第一篇博客,就到这吧,收!!!!!!