I’ve been busy working away on a new XPages
application in work that implements a typical shopping cart like you might
find on Amazon or other online retail websites. When I started planning
the application I hit upon the idea of storing the items that the user
had added to the shopping cart into a variable in the sessionScope. The
sessionScope, in xPages, is an area of memory that you can store values
into the application has their own sessionScope as opposed to the applicationScope
that is shared across all users of the xPages application. My idea was
that by using the session scope I wouldn’t have to create any temporary
backend documents to store the selected items.
Normally you put stuff into the sessionScope
using the ‘put’ method, for example sessionScope.put("userFirstName","Declan").
You can also write this in shorthand as sessionScope.userFirstName = "Declan".
To get stuff out of the sessionScope you use the get method, for example
sessionScope.get("userFirstName") or in shorthand sessionScope.userFirstName
inside a variable including another object. Based on the ‘Namespacing
Scoped Variables‘ blog entry by Tim Tripcony I figured that
I’d be able to use my sessionScope to store an array of Unique ID’s and
their quantities. After talking with Tim about the idea he suggested that
I put a hashmap object into my variable in the sessionScope.
To initialize the variable I’m using
the following line of code.
= (sessionScope.cartItems || new java.util.HashMap());
This sets the sessionScope.cartItems
to be equal to itself so that I don’t accidentally clear it’s value, however
if sessionScope.cartItems does not exist yet then the second half of the
statement is carried out which created the HashMap object in the sessionScope.
Now that I have a hashmap inside the
sessionScope I can use all the methods on it as I would the sessionScope
var thisQuantity = getComponent("comboBox1").getValue();
By using the UNID as the key I can easily
relate the item in the cart back to the item documents in my notes database.
I can even use a repeat control bound to sessionScope.cartItems.keySet();
loop through all the items in the shopping cart. I could use sessionScope.cartItems.size();
to find out how many items are in the shopping cart and even sessionScope.cartItems.clear();
to empty the cart out.
Hopefully knowing that you can store
different types of objects in the sessionScope will give you some ideas
for your own applications.