Ognl 语法使用探究
在struts2中大量使用了OGNL 语法,当然,想学好struts当然要了解OGNL,于是开始学习了OGNL之旅。废话不多说。
直接切入主题。
我将根据OGNL的作用一一阐述和举例:
首先:
一些基本语法:
?
?
?
一,读取类属性
?
?
二,写类属性
?
?
三,读写常量
?
?
四,用构造函数创建集合类
?
?
/** * <pre> * 测试构造collection * 参考http://www.opensymphony.com/ognl/html/LanguageGuide/projection.html * </pre> * * @author yajun.wuyj */public class OgnlCollectionConstructTest { public static void main(String[] args) throws OgnlException { // 创建链表 List list = (List) Ognl.getValue("{ null,"Untitled"}", null); System.out.println(list); // 创建数组 int[] array = (int[]) Ognl.getValue("new int[] { 1, 2, 3 }", null); System.out.println(array[2]); // 创建map Map map = (Map) Ognl.getValue("#{ "foo" :"foo value", "bar" : "bar value" }", null); System.out.println(map); }}??
?
五,
?
?
/** * <pre> * 测试针对所有的elements 调用方法 * 参考http://www.opensymphony.com/ognl/html/LanguageGuide/projection.html * </pre> * * @author Administrator */public class OgnlProjectingTest { public static void main(String[] args) throws OgnlException { List<String> strings = new ArrayList<String>(); strings.add("1"); strings.add("2"); strings.add("3"); System.out.println(Ognl.getValue("{ #this instanceof String ? #this : #this.toString()}", strings)); }}?六,
?
?
/** * <pre> * 挑选指定的元素作为新的的集合 * 参考:http://www.opensymphony.com/ognl/html/LanguageGuide/selection.html * </pre> * * @author Administrator */public class OgnlSelectingTest { public static void main(String[] args) throws OgnlException { OgnlContext context = new OgnlContext(); List lists = new ArrayList(); lists.add("string 1"); lists.add(Integer.valueOf(1)); lists.add("string 2"); context.put("lists", lists); // 找出所有的string System.out.println(Ognl.getValue("lists.{? #this instanceof String}", context)); // 找出第一个string System.out.println(Ognl.getValue("lists.{^ #this instanceof String}", context)); // 找出最后一个string System.out.println(Ognl.getValue("lists.{$ #this instanceof String}", context)); }}??
?
?
==========================
?
struts2中的context中,如果多个属性相同???