Arrays in OGNL

Arrays in OGNL

July 10, 2013

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:





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:





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:


  1. Introduction to OGNL
  2. A simple OGNL expression
  3. Declaring variables in OGNL
  4. Method calls in OGNL
  5. Arrays in OGNL
  6. OGNL: What about those curly braces?
  7. Looping in OGNL
  8. Looping in OGNL take 2
  9. So what exactly is #this in OGNL?
  10. A continuing look at #this variable in OGNL
  11. Functions in OGNL
  12. Misc Topics in OGNL

John DaSilva develops training and solutions at Ping Identity.