Web Storage API
- Local Storage
- Session Storage
- Setting Key-Value Pairs
- Removing Key-Value Pairs
- Clearing Storage
- Getting Values from Storage
The WebStorage
API allows you to access the browser Web Storage from the server. Web Storage is a standard JavaScript API to store string-only key-value pairs in the device running the browser. Data is persisted only in that device.
WebStorage.Storage
defines two types of storage: local storage and session storage.
Note
|
Default Value
WebStorage uses UI.getCurrent() by default to get a target UI instance. All methods also have variants with a parameter for UI instance. The UI instance argument shouldn’t be null — especially when calling a method outside of the main thread.
|
Local Storage
Local storage data is stored per origin — a combination of protocol, host, and port — with no expiration date.
Shortcuts: setItem(String, String)
, removeItem(String)
, and clear()
.
The following code sets a key-value pair to local storage:
WebStorage.setItem("key", "value");
Session Storage
Session storage data is stored per origin and browser page session, i.e., the browser window or tab. Storage is cleared when the window or tab is closed.
Note
|
Storage Term
Session storage term comes from the Window.sessionStorage Web Storage JavaScript API. It’s not directly affected by the lifecycle of Vaadin sessions or HTTP sessions in general.
|
Setting Key-Value Pairs
Key-value pairs are set in the storage with setItem(Storage, String, String)
. You’d do that like this:
WebStorage.setItem(Storage.LOCAL_STORAGE, "key", "value");
Removing Key-Value Pairs
You can remove key-value pairs from storage with removeItem(Storage, String)
. Below is an example of this:
WebStorage.removeItem(Storage.SESSION_STORAGE, "key");
Clearing Storage
Clear storage with clear(Storage)
. Below is an example:
WebStorage.clear(Storage.SESSION_STORAGE);
Getting Values from Storage
You can request a value from storage by using a key. You can process the returned value using a callback with getItem(Storage, String, Callback)
. Below is example of how to get a value from the session storage with a key:
WebStorage.getItem(Storage.SESSION_STORAGE, "key", value -> {
System.out.println(value);
});
Callback gives a null value in case of an unexpected error.
08b13e40-3845-11ee-be56-0242ac120002