OGNL(Object Graphic Navigation Language)在Struts中广泛应用,用来在 JSP页面中显示Action中的数据,当然,Struts肯定要对OGNL做一些扩充,这里我们讲解一下OGNL的几个简单方法。
第一步: 新建java project ,在项目中引入相关的JAR包:ognl-3-0-4.jar与javassist-3.11.0.jar
第二步:建立另个普通的类,这里就叫做Test1与Test2吧,并为之生成get和set方法,如下:
public class Test1
{
private String name;
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
}
public class Test2
{
private String name;
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
}
编写OGNLTest测试类
import ognl.*; //引入ognl包
public class OGNLTest
{
public void main(String args[])
{
Test1 test1=new Test1() //实例化Test1
test1.setName("test1");
Test2 test2=new Test2();
test2.setName("test2");
OgnlContext context=new OgnlContext(); //代表OGNL上下文,它实现了java.util.Map接口
context.setRoot(test1); //OGNL上下文只能存在唯一的一个叫做根的对象,可以指定也可以不指定
context.put("test1",test1);
context.put("test2",test2); //这两句是向OGNL当前上下文中添加对象,这里由于test1已经添加为根了,可以不添加
Object object=context.parseExpression("name"); //由OGNL当前上下文解析要获取对象的属性名字
//获取属性值,由于在解析属性时,未指定类名,则OGNL会在根对象中寻找,看是否有相应的get方法,有则返回属性值,无则抛出异常。
Object object2=context.getValue(object,contex,context.getRoot());
System.out.println(object2); //会打印出test1
//如果要想获取某个对象的属性值,需要在对象前边加一个#号,用来表示让OGNL去查找相应对象,后边用.加上属性
Object object3=cotext.parseExpression("#test2.name");
Object object4 =context.getValue(object3,context,context.getRoot()); //获取test2的name属性值
System.out.println(object4); //会打印出test2
}
}