OGNL Part 4: Lists and Arrays

In the part 3, we’ve discussed about Maps. In this blog, let’s look at how to create array and lists. The most common thing is both are accessible via index.

package au.com.ojitha.ongl;

import java.util.List;

import ognl.Ognl;
import ognl.OgnlException;

public class BasicListExample {

	/**
	 * @param args
	 * @throws OgnlException
	 */
	public static void main(String[] args) throws OgnlException {
		// List
		List<String> list = (List) Ognl.getValue("{'a','b','c'}", null);
		System.out.println(list + " is size of " + Ognl.getValue("size", list));
		System.out
				.println("The third element is " + Ognl.getValue("[2]", list));

		// array
		Integer[] intValues = (Integer[]) Ognl.getValue("new Integer[]{1,2,3}",
				null);
		System.out.println("Size of the array is "
				+ Ognl.getValue("length", intValues));
		System.out.println("The third element is "
				+ Ognl.getValue("[2]", intValues));

		// in expression
		System.out.println(Ognl.getValue("2 in {1,2}", null));
		// call the method to get the int value of the root object
		System.out.println(Ognl
				.getValue("intValue() in {1, 2}", new Integer(2)));

		int val = 2;

		// use variables
		System.out.println("Check the val=" + val + " then #val in {1,2}"
				+ Ognl.getValue("#val=" + val + ", #val in {1,2}", null));

	}

}

As shown in the above code, line 16shows how to initialize the List. In the line 17, access the size() method and in the line 19 access the element by the index. In the line 22 create a Integer array and access the length property (length property is very bad idea in Java according to me. I am sure OGNL programmers had difficulty) and in the line 26-27 access the array using index as in the List. Lines 30-40, I played with “in” which is specific to the OGNL. In the lines 38-39, I used variable.

See the output

[a, b, c] is size of 3
The third element is c
Size of the array is 3
The third element is 3
true
true
Check the val=2 then #val in {1,2}true

Comments

Popular posts from this blog

How To: GitHub projects in Spring Tool Suite

Spring 3 Part 7: Spring with Databases

Parse the namespace based XML using Python