Java根据Session Id获取Session对象(转转)

假如想象 提交于 2019-12-14 19:08:21

原csdn blog 链接:https://blog.csdn.net/benweizhu/article/details/8282486
最初始的链接:http://sizeed.blog.163.com/blog/static/96525451201211621943403/

有点懒直接复制了

import javax.servlet.http.HttpSession;
import java.util.HashMap;
 
/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 12-12-11
 * Time: 上午10:57
 * To change this template use File | Settings | File Templates.
 */
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);
	}
 
}
package com.zeph.jsp.servlet;
 
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.HashMap;
import java.util.Map;
 
/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 12-12-11
 * Time: 上午10:58
 * To change this template use File | Settings | File Templates.
 */
public class SessionListener implements HttpSessionListener {
	public static Map userMap = new HashMap();
	private MySessionContext myc = MySessionContext.getInstance();
 
	public void sessionCreated(HttpSessionEvent httpSessionEvent) {
		myc.AddSession(httpSessionEvent.getSession());
	}
 
	public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
		HttpSession session = httpSessionEvent.getSession();
		myc.DelSession(session);
	}
}

在web.xml中配置

<listener>
        <listener-class>com.zeph.jsp.servlet.SessionListener</listener-class>
  </listener>

使用:

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

另一种方法:https://www.cnblogs.com/blog411032/p/5909095.html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!