OGNL Part 3: How to read Map

In this example, explains how the OGNL access the Map.  Refer to the part 2 for basic understanding of navigation chain.

import java.util.HashMap;
import java.util.Map;

import ognl.Ognl;
import ognl.OgnlException;

public class SecondExample {

	/**
	 * @param args
	 * @throws OgnlException 
	 */
	public static void main(String[] args) throws OgnlException {
		
		Map<String, String> mapValues = new HashMap<String, String>();
		mapValues.put("lname", "Kumanayaka");
		mapValues.put("fname", "Ojitha");

		System.out.println(Ognl.getValue("fname+' '+ lname", mapValues));
	}

}
OGNL always treat different kind of objects differently.

Instead of accessing Map as in line 16 and 17, you can use OGNL to initialize the map as shown in the line 19 in the following code.

package au.com.ojitha.ongl;

import java.util.Map;

import ognl.Ognl;
import ognl.OgnlException;

public class SecondExample {

	/**
	 * @param args
	 * @throws OgnlException 
	 */
	public static void main(String[] args) throws OgnlException {
		
		Map<String, String> mapValues = null;
		//mapValues.put("lname", "Kumanayaka");
		//mapValues.put("fname", "Ojitha");
		mapValues = (Map)Ognl.getValue("#{'lname': 'Kumanayaka', 'fname':'Ojitha'}", null);

		System.out.println(Ognl.getValue("fname+' '+lname", mapValues));
	}

}

In the line 19, you can explicitly define the Map implementation to use as shown in the following code.

package au.com.ojitha.ongl;

import java.util.Map;

import ognl.Ognl;
import ognl.OgnlException;

public class SecondExample {

	/**
	 * @param args
	 * @throws OgnlException 
	 */
	public static void main(String[] args) throws OgnlException {
		
		Map<String, String> mapValues = null;
		//mapValues.put("lname", "Kumanayaka");
		//mapValues.put("fname", "Ojitha");
		mapValues = (Map)Ognl.getValue("#@java.util.LinkedHashMap@{'lname': 'Kumanayaka', 'fname':'Ojitha'}", null);

		System.out.println(Ognl.getValue("fname+' '+lname", mapValues));
	}

}

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