import java.util.HashMap;
import java.util.Map; import javax.servlet.http.HttpSession; /**
*
* ClassName: SessionContext
*
* @Description: 获取sessionID
* @author liangbo
* @date 2016-3-18
*/
public class SessionContext { private static SessionContext instance;
private Map<String, HttpSession> sessionMap; private SessionContext() {
sessionMap = new HashMap<String, HttpSession>();
} public static SessionContext getInstance() {
if (instance == null) {
instance = new SessionContext();
}
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);
}
}
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener; /**
*
* ClassName: SessionListener
*
* @Description: sessionid web.xml监听器
* @author liangbo
* @date 2016-3-18
*/
public class SessionListener implements HttpSessionListener { private SessionContext context = SessionContext.getInstance(); @Override
public void sessionCreated(HttpSessionEvent sessionEvent) {
context.addSession(sessionEvent.getSession());
} @Override
public void sessionDestroyed(HttpSessionEvent sessionEvent) {
HttpSession session = sessionEvent.getSession();
context.delSession(session);
} }
web.xml
<listener>
<listener-class>hometree.ecs.business.service.util.session.SessionListener</listener-class>
</listener>
//添加session
SessionContext.getInstance().addSession(server.getSession()); //获取session
HttpSession session = SessionContext.getInstance().getSession(
request.getParameter("sessionid"));