Skip to content

Instantly share code, notes, and snippets.

@robatron
Last active March 30, 2018 20:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robatron/5971824 to your computer and use it in GitHub Desktop.
Save robatron/5971824 to your computer and use it in GitHub Desktop.
Storing and accessing server-side JSP variables for client-side JavaScript consumption via a custom JSP tag that uses HTML5 `localStorage`

Set server-side variables in your JSP template via a js:clientStore custom tag for consumption by the JavaScript:

<%-- Arbitrary JSP variables --%>
<c:set var="a" val="1" />
<c:set var="b" val="2" />
<c:set var="c" val="3" />

<%-- Store the "a" and "b" JSP variables under "my.namespace" --%>
<js:clientStore 
    namespace = "my.namespace" 
    vals = "${[a, b]}" />

<%-- Store the "c" JSP variable under "my.namespace.foo" --%>
<js:clientStore 
    namespace = "my.namespace.foo" 
    vals = "${c}" />

The js:clientStore tags would render a script tag that uses HTML5 localStorage to save JSON-serialized JSP variables:

<script>
    localStorage.setItem('my.namespace', '{"a":"1","b":"2"}');
    localStorage.setItem('my.namespace.foo', '{"c":"3"}');
</script>

Which can be accessed later from JavaScript, e.g.:

// Grab references to your namespaces
var rootServerProps = new ClientStore('my.namespace');
var fooServerProps = new ClientStore('my.namespace.foo');

// Access after document is ready to assure all localStorage calls have completed
$(document).ready(function(){
    rootServerProps.get('a'); // Would return "1"
    rootServerProps.get('b'); // Would return "2"
    fooServerProps.get('c');  // Would return "3"
});
@codetothepoint
Copy link

hi

@nandanraj56
Copy link

How to access localstorage in java

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment