As discussed above, the "indexing" notation is actually just property reference, though a computed form of property reference rather than a constant one.
For example, OGNL internally treats the "array.length" expression exactly the same as this expression:
array["length"]
And this expression would have the same result (though not the same internal form):
array["len" + "gth"]
For Java arrays and Lists indexing is fairly simple, just like in Java. An integer index is given and that element is the referrent. If the index is out of bounds of the array or List and IndexOutOfBoundsException is thrown, just as in Java.
JavaBeans supports the concept of Indexed properties. Specifically this means that an object has a set of methods that follow the following pattern:
public PropertyType
[] getPropertyName
()
public void setPropertyName
(PropertyType
[] anArray)
public PropertyType
getPropertyName
(int index)
public void setPropertyName
(int index, PropertyType
value)
OGNL can interpret this and provide seamless access to the property through the indexing notation. References such as
someProperty[2]
are automatically routed through the correct indexed property accessor (in the above case through getSomeProperty(2)
or setSomeProperty(2, value)
). If there is no indexed property
accessor a property is found with the name someProperty
and the index is applied to that.
OGNL extends the concept of indexed properties to include indexing with arbitrary objects, not just integers as with JavaBeans Indexed Properties. When finding properties as candidates for object indexing, OGNL looks for patterns of methods with the following signature:
public PropertyType
getPropertyName
(IndexType
index)
public void setPropertyName
(IndexType
index, PropertyType
value)
The PropertyType
and IndexType
must match each other in the corresponding set and get methods. An actual example of using Object Indexed Properties is with the Servlet API:
the Session object has two methods for getting and setting arbitrary attributes:
public Object getAttribute(String name) public void setAttribute(String name, Object value)
An OGNL expression that can both get and set one of these attributes is
session.attribute["foo"]