提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
当两次访问的方法不同时,后台的session是不一样的,也就是说sessionId,不一致,所以导致的问题就是:当我需要从session取值的时候,出现取不到值的情况.
通过sessionId和前端进行交互,来保证每一次的session是一致的
一、以前解决方法
HttpSession sess = session.getSessionContext().getSession(sid)
二、新的解决方法
1、创建自己的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);
}
}
2、建立session监听,要实现HttpSessionListener接口
public class SessionListener implements HttpSessionListener {
private MySessionContext myc = MySessionContext.getInstance();
public SessionListener() {
}
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
HttpSession session = httpSessionEvent.getSession();
myc.addSession(session);
}
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
HttpSession session = httpSessionEvent.getSession();
myc.delSession(session);
}
}
接下来就可以通过这种方式来取得
MySessionContext myc= MySessionContext.getInstance();
HttpSession sess = myc.getSession(sessionId);
文章介绍了在处理前后端session不一致问题时,从传统的解决方案到采用自定义sessionContext和实现HttpSessionListener接口的新方法。通过创建自己的session管理类存储和删除session,以及监听session的创建与销毁,确保能正确获取和管理session。
552

被折叠的 条评论
为什么被折叠?



