Saturday, January 7, 2012

Declaring global variable in XPage using dataContexts

While working on a XPages application I required a database object to be initialized and then used in various controls in XPage. I wanted to initialize the object only once then use it again and again. With some experimenting I found out that if I put the initialization code in beforePageLoad, afterPageLoad or beforeRenderResponse I was able to access the object from anywhere in XPage. But I wasn't sure that whether this was the correct way or the objects would get automatically garbage collected. So I posted this question on XPages forum.

Paul S. Withers suggested me to use dataContexts. You can find them in All Properties tab of XPages properties inside data section.

To use it you need only two properties:
  1. var: Name by which you want to reference the object
  2. value: Value that you want to assign to the object in SSJS
Here I created object named myDB and initialized it to a database object. Now this object can be used in any control inside XPage including controls inside the custom controls embedded inside the XPage. The XPage source shows the following code snippet with <xp:dataContext> tag.

You can also find this property inside custom control and panel.

Update 30 Jan 2012: I had marked my query of declaring global variables in XPages on forum as resolved but apparently people were still responding to it and due to which an interesting thing came out. Tom Sparrow found out that storing Domino objects in dataContexts could result in Serialization exception. The XPages Control Documentation for xp:dataContext states that it "Provides a value using the specified request scope variable" (missed that completely the first time I read it) and you should not use a scope variable to store Domino object. So I guess I will stick with declaring global Domino objects in beforePageLoad, afterPageLoad or beforeRenderResponse. For declaring other non-Domino objects we can still use dataContexts. Thanks to Tom for pointing out this one :)


  1. Just a warning that there may be problems with this approach (or more likely I may be doing something wrong).

    See my comment on the XPages forum thread linked in the article.

    1. Thanks for pointing this one out! I have updated the entry.

  2. How is declaring global Domino objects in beforePageLoad, afterPageLoad or beforeRenderResponse working for you? I tried it with a custom Java object which contains Domino objects and am getting "NotesException: Object has been removed or recycled".

    1. I kind of moved away from declaring global objects. I did too face similar issues with Domino objects, but infrequently. It seems that even if objects are declared in 'beforePageLoad', 'afterPageLoad' or 'beforeRenderResponse' they are recycled by garbage collection.