ShowTable of Contents
Here are some random tips for working with ServerSide JavaScript.
Convert to and from JSON
You can convert a JavaScript object to JSON and back using build-in methods:
var json = toJson( {a:[1,2,3]} ) //-> '{"a":[1,2,3]}'
var jsObj = fromJson( '{"a":[1,2,3]}' ) //-> {a:[1,2,3]}
isJson( '{"a":[1,2,3]}' ) //-> true
Example found at Tommy Valand
.
Access user's HTTP session
You can access a user's session object with this code:
var sess = facesContext.getExternalContext().getRequest().getSession();
a session has the following useful methods:
sess.getAttribute(name) // returns an attribute
sess.getAttributeNames() // returns all available attributes as java.util.Enumeration
sess.getCreationTime() // returns the time when the session was created
sess.getId() // returns the session ID
sess.getLastAccessedTime() // returns the time of the last user activity
sess.getMaxInactiveInterval() // returns the max amount of seconds the user is allowed to be inactive
sess.isNew() // true if the client created a new session, false if the client re-entered a previous session
sess.invalidate() // resets the session
sess.removeAttribute(name) // removes an attribute
sess.setAttribute(name, obj) // sets an attribute
sess.setMaxInactiveInterval(interval) // sets the max inactive interval, in seconds
to get all attributes and their types:
var sess = facesContext.getExternalContext().getRequest().getSession();
var attr = sess.getAttributeNames();
var result = "";
while( attr.hasMoreElements() ){
var elem = attr.nextElement();
result += elem + ": ";
result += sess.getAttribute(elem);
result += " [";
result += typeof(sess.getAttribute(elem));
result += "]";
}
Thanks to Sven Hasselbach