在过去,当我遇到相同的问题时,我决定实现一个Singleton模式,以使用户当前的会话保持“全局”。这样,我就可以访问我需要的任何课程中的当前会话。
应该是这样的:
public class SessionManager { private static SessionManager instance; private Session currentSession; // this object holds the session data (user, host, start time, etc) private SessionManager(){ ... } public static SessionManager getInstance(){ if(instance == null){ instance = new SessionManager(); } return instance; } public void startNewSession(User user){ // starts a new session for the given User } public void endCurrentSession(){ // here notify the server that the session is being closed } public Session getCurrentSession(){ return currentSession; }}然后我调用
endCurrentSession()内部
windowClosing()方法,如下所示:
public void windowClosing(WindowEvent e) { SessionManager.getInstance().endCurrentSession();}注意:
在此调用此方法将在事件分配线程中执行,导致GUI“冻结”,直到完成此方法为止。如果您与服务器的交互花费很长时间,则需要在单独的线程中进行。



