GWTでWeb Storageを利用する
GWTではWeb Storageを利用するためのAPIが用意されている。(ただし、Experimental API)
http://kumo2ji.appspot.com/
では、実験的にCellBrowserのWidthをユーザーごとに記憶するために利用している。
CellBrowserの幅を変更した場合、次回以降はその幅で初期化される。
public class Config { private StorageMap storageMap = null; private static String CELL_BROWSER_KEY = "cellBrowser"; public Config() { Storage storage = Storage.getLocalStorageIfSupported(); if (storage != null) { storageMap = new StorageMap(storage); } } public double getCellBrowserSize() { if (storageMap == null || !storageMap.containsKey(CELL_BROWSER_KEY)) { return 300; } String size = storageMap.get(CELL_BROWSER_KEY); return Double.valueOf(size); } public void setCellBrowserSize(double size) { if (storageMap == null) { return; } storageMap.put(CELL_BROWSER_KEY, String.valueOf(size)); } }
初期化は
Storage storage = Storage.getLocalStorageIfSupported(); if (storage != null) { storageMap = new StorageMap(storage); }
で行う。
保存できるのは文字列のみなので、保存したいものが数値の場合は、
storageMap.put(CELL_BROWSER_KEY, String.valueOf(size));
のように文字列にしてからputする。
getする場合も
String size = storageMap.get(CELL_BROWSER_KEY);
return Double.valueOf(size);
として、返す。