OGNL三要素: 表达式 、OgnlContext 上下文、Root 根
1.支持对象操作
@Test
public void test1() throws OgnlException {
//1.获取上下文对象OgnlContext
OgnlContext context = new OgnlContext();
//2.操作
Object root = context.getRoot();
Object value = Ognl.getValue("'hello'.length()", context, root);
System.out.println(value);
}
2.支持静态成员访问
@Test
public void test2() throws OgnlException {
OgnlContext context = new OgnlContext();
Object value = Ognl.getValue("@java.lang.Math@random()", context, context.getRoot());
Object value2 = Ognl.getValue("@java.lang.Math@PI", context, context.getRoot());
System.out.println(value);
System.out.println(value2);
}
3.访问Ognl上下文(如果从根中获取数据,不需要添加#号,如果不是从根中获取,需要#)
@Test
public void test3() throws OgnlException {
//1.获取上下文对象
OgnlContext context = new OgnlContext();
//2.向上下文中存储数据
context.put("username","tom");
//3.操作
//如果从根中获取数据,不需要添加#号,如果不是从根中获取,需要#
Object value = Ognl.getValue("#username", context, context.getRoot());
System.out.println(value);
}
@Test
public void test4() throws OgnlException {
//1.获取上下文对象
OgnlContext context = new OgnlContext();
//2.存储数据
Map<String,String> map = new HashMap<String,String>();
map.put("username", "Jane");
//将map存储到context的根中
context.setRoot(map);
//操作
//如果从根中获取数据,不需要添加#号,如果不是从根中获取,需要#
Object value = Ognl.getValue("username", context, context.getRoot());
System.out.println(value);
}
4.操作集合(支持赋值操作与表达式串联)
@Test
public void test1() throws OgnlException {
//1.获取上下文对象OgnlContext
OgnlContext ognlContext = new OgnlContext();
//2.操作
//相当于创建了一个List集合
Object value = Ognl.getValue("{'hello','world','well'}", ognlContext, ognlContext.getRoot());
ognlContext.setRoot(value);
//3.获取list中的第一个值
System.out.println(Ognl.getValue("[0]",ognlContext, ognlContext.getRoot()));
}
@Test
public void test2() throws OgnlException {
//1.获取上下文对象OgnlContext
OgnlContext ognlContext = new OgnlContext();
//2.操作
//相当于创建了一个map集合
Object value = Ognl.getValue("#{'username':'tom','age':23}", ognlContext, ognlContext.getRoot());
ognlContext.setRoot(value);
//3.获取map中的值
System.out.println(Ognl.getValue("username", ognlContext,ognlContext.getRoot()));
//只会返回最后一个属性的值,即age=20
System.out.println(Ognl.getValue("username='Jane',age=20", ognlContext,ognlContext.getRoot()));
}