11.14. Accessing Session-Global Data
Applications typically need to access some objects from practically all user interface code, such as a user object, a business data model, or a database connection.This data is typically initialized and managed in the UI class of the application, or in the session or servlet.
For example, you could hold it in the UI class as follows:
class MyUI extends UI { UserData userData;
public void init() {
userData = new UserData();
}
public UserData getUserData() { return userData;
}
}
Vaadin offers two ways to access the UI object: with getUI() method from any component and the global UI.getCurrent() method.
The getUI() works as follows:
data = ((MyUI)component.getUI()).getUserData();
This does not, however work in many cases, because it requires that the components are attached to the UI.That is not the case most of the time when the UI is still being built, such as in constructors.
class MyComponent extends CustomComponent { public MyComponent() {
// This fails with NullPointerException Label label = new Label("Country: " +
getApplication().getLocale().getCountry());
setCompositionRoot(label);
}
}
The global access methods for the currently served servlet, session, and UI allow an easy way to access the data:
data = ((MyUI) UI.getCurrent()).getUserData();
The Problem
The basic problem in accessing session-global data is that the getUI() method works only after the component has been attached to the application. Before that, it returns null.This is the case in constructors of components, such as a CustomComponent:
Using a static variable or a singleton implemented with such to give a global access to user session data is not possible, because static variables are global in the entire web application, not just the user session. This can be handy for communicating data between the concurrent sessions, but creates a problem within a session.
The data would be shared by all users and be reinitialized every time a new user opens the application.