struts-OGNL2

OGNL构成三要素:

1.表达式

表达式会规定OGNL操作到底要“干什么”;OGNL不仅支持链式描述对象访问路径,还支持在表达式中进行简单的计算,甚至还支持Lambda表达式;

2.root对象

OGNL的root对象可以理解为OGNL的操作对象,表名"对谁干";OGNL的root对象实际上是一个java对象,是所有OGNL操作的实际载体。这意味着如果有一个OGNL表达式,那么我们实际上是针对root对象来进行OGNL表达式的计算并返回结果。

3.上下文环境;

有了root和表达式,其实我们已经可以开始进行OGNL的基本功能了。不过事实上在OGNL内部,所有的操作都会在一个特定的数据环境中进行,这个数据环境就是OGNL的上下文环境;其实这个上下文环境规定了OGNL的操作“在哪里干”;

OGNL的上下文环境是一个Map结构,称之为OgnlContext,root对象也会被添加到这个环境中,并且被当做一个特殊的对象进行处理。

OGNL本身没有数据结构的概念,OGNL仅仅是提供了一些对数据进行操作的方法;

OGNL基本操作:

1.针对root对象的访问

针对root对象的对象树的访问是通过使用“点号”将对象的引用串联起来实现的。

通过这种方式,OGNL实际上将一个树形的对象结构转化成一个链式结构的字符串来表达语义;

2.对上下文基本环境的访问             

#introduction

其他的基本操作,请参照:

http://zhujianguo1981.iteye.com/admin/blogs/1746726

深入this指针

this指针是许多编程语言都具备的特殊关键字。绝大多数语言中的this指针的含义都类似,表示“当前所在函数的调用者”。

#符号的三种用途:

(1)加在普通OGNL表达式前面,用于访问OGNL上下文的变量;

(2)使用#{}语法动态构建Map;

(3)加在this指针前表示对this指针的引用;

实例代码如下:

public class BasicOgnlTest {

public void testGetValue() throws Exception{

//创建Root对象

User user = new User();

user.setId(1);

user.setName("downpour");

//创建上下文环境

Map context = new HashMap();

context.put("introduction", "my name is");

//从root对象中获取name值

//Ognl.parseExpression("name"),将name转化为OGNL表达式

Object name = Ognl.getValue(Ognl.parseExpression("name"), user);

System.out.println((String)name);

//直接写OGNL表达式获取name值

Object name1 = Ognl.getValue("name", user);

System.out.println((String)name1);

//从上下文环境中获取introduction

Object contextValue = Ognl.getValue(Ognl.parseExpression("#introduction"), context,user);

System.out.println((String)contextValue);

//测试同时从将ROOT对象和上下文环境作为表达式的一部分进行计算

Object hello = Ognl.getValue(Ognl.parseExpression("#introduction + name"), context,user);

System.out.println((String)hello);

}

public void testSetValue() throws Exception{

User user = new User();

user.setId(1);

user.setName("downpour");

//对ROOT对象进行写值操作

// Ognl.setValue("group.name", user, "dev");

//对root对象user的age属性赋值为18

Ognl.setValue("age",user, "18");

//TODO

// Object temp = Ognl.getValue(Ognl.parseExpression("group.name"), user);

// System.out.println((String)temp);

Object temp1 = Ognl.getValue(Ognl.parseExpression("age"), user);

System.out.println(temp1);

Object temp2 = Ognl.getValue("age", user);

System.out.println(temp2);

}

public static void main(String [] args){

try{

BasicOgnlTest bot = new BasicOgnlTest();

bot.testGetValue();

bot.testSetValue();

}catch(Exception ex){

ex.printStackTrace();

}

}

}


猜你喜欢

转载自zhujianguo1981.iteye.com/blog/1747252