在struts2中大量使用了OGNL 语法,当然,想学好struts当然要了解OGNL,于是开始学习了OGNL之旅。废话不多说。
直接切入主题。
我将根据OGNL的作用一一阐述和举例:
首先:
一些基本语法:
- 常量: 字符串:“ hello ” 字符:‘ h ’ 数字:除了像 java 的内置类型 int,long,float 和 double,Ognl 还有如例:10.01B,相当于 java.math.BigDecimal,使用’ b ’或者’ B ’后缀。 100000H,相当于 java.math.BigInteger,使用’ h ’ 或 ’ H ’ 后缀。
- 属性的引用 例如:user.name
- 变量的引用 例如:#name
- 静态变量的访问 使用 @class@field
- 静态方法的调用 使用 @class@method(args), 如果没有指定 class 那么默认就使用 java.lang.Math.
- 构造函数的调用 例如:new java.util.ArrayList();
一,读取类属性
二,写类属性
三,读写常量
四,用构造函数创建集合类
/**
* <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);
}
}
五,
Projecting Across Collections
/**
* <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));
}
}
六,
Selecting From Collections
/**
* <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中,如果多个属性相同???