In the past when I faced the same issue, I decided to implement a Singleton pattern to keep the user's current session "global". This way I have access to the current session in any class I need.
It should be something like this:
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;
}
}
Then I call endCurrentSession()
inside windowClosing()
method, like this:
public void windowClosing(WindowEvent e) {
SessionManager.getInstance().endCurrentSession();
}
Note: calling this method here will execute in the Event Dispatch Thread causing GUI "freezes" until this method is done. If your interaction with the server takes a long time, you'd want to make this in a separate thread.