OGNL provides many options for dealing with arrays in an expression. The Apache Commons language guide on OGNL in the section on arrays covers this in some detail, though it may leave you with more questions than answers.
For this article in the series I am going to focus on the simplest way to use an array in an expression. In a future article we may get fancier, particularly if you let me know that I should.
See the complete list of articles in my OGNL series at the end of this entry.
You can think of an array as a collection of objects or primitives in OGNL, although it is not a necessarily a java.util.Collection.
You can get the size of an array by using the length property, as in the following expression:
array.length
To access a specific element you use the standard array syntax, as in the following example. Here, to access the first element you would use:
array[0]
Note from the above that arrays are zero based, meaning a reference to the first element in the array is always 0, and the last element in the array would be length -1, as in this example:
array[array.length - 1]
The following code shows what we covered above in one OGNL expression. Although this is a made up example it should give you some idea of what you can do with arrays.
#array = #this.get("subject").toString().getBytes(),
array[array.length - 1] = array[0],
"The length of attribute 'subject' is: " + array.length + " Byte value 0 is : " + array[0] + " The expression 'array[array.length - 1] = array[0]' replaces last byte with first byte giving you: " + new String(array).toString()
And an example of it in action:
Stay tuned for more about OGNL. In the meantime please leave a comment on this post and let me know what topics you would like to see. Follow me on Twitter: @jdasilvaPI
****************************************
OGNL Blog Series:
- Introduction to OGNL
- A simple OGNL expression
- Declaring variables in OGNL
- Method calls in OGNL
- Arrays in OGNL
- OGNL: What about those curly braces?
- Looping in OGNL
- Looping in OGNL take 2
- So what exactly is #this in OGNL?
- A continuing look at #this variable in OGNL
- Functions in OGNL
- Misc Topics in OGNL
John DaSilva develops training and solutions at Ping Identity.