I have an application with login screen, after the user is authenticated some "data" is retrieved from a database (username and privileges), until here everything is well.
After the login process I need to access to the privileges to generate some menus across different JavaFX scenes, this all throughout the entire application in any moment, but I don´t know how to do it.
What I am looking for is a behavior such as SESSION variable in PHP (yep, I come from web development), which keeps information alive and accesible during a certain period of time (usually while user is logged in).
The information I have found about this topic is unclear and outdated, I mean, solutions that do not apply for JavaFX 2 or solutions with old design patterns.
I have created an image because in other forums I have found the same question but that is misunderstood, so I hope this could help.
Thanks to everyone.
You can use singleton design patter. For example:
public final class UserSession {
private static UserSession instance;
private String userName;
private Set<String> privileges;
private UserSession(String userName, Set<String> privileges) {
this.userName = userName;
this.privileges = privileges;
}
public static UserSession getInstace(String userName, Set<String> privileges) {
if(instance == null) {
instance = new UserSession(userName, privileges);
}
return instance;
}
public String getUserName() {
return userName;
}
public Set<String> getPrivileges() {
return privileges;
}
public void cleanUserSession() {
userName = "";// or null
privileges = new HashSet<>();// or null
}
@Override
public String toString() {
return "UserSession{" +
"userName='" + userName + '\'' +
", privileges=" + privileges +
'}';
}
}
and use the UserSession whenever you need. When you do login you just call: UserSession.getInstace(userName, privileges)
and when you do log out: UserSession.cleanUserSession()