Ognl 笔记

1、Ognl简介

OGNL的全称是Object Graph Navigation Language(对象图导航语言),它是一种强大的表达式语言。

 

它存在着两种对象,一种为根对象、一种为非根对象。根对象只有一个,而非根对象可以有多个。这里就有一个表达式:

       Ognl的上下文(OgnlContext)= 根对象(1)+非根对象(N)

 

2、存值与取值

第一步肯定是导入ognl的jar包。

 

根对象与非根对象的区别: 1、根对象只有一个;非根对象有多个

                                             2、根对象取值,直接根据属性名取;非根对象取值时,需要在前面加入’#‘ 号,如下:

public static void main(String[] args) {
		// 申明一个Ognl的上下文
		OgnlContext oc=new OgnlContext(); 
		// 向上下文内添加非根对象
		oc.put("s1", new Student("1", "张三"));
		oc.put("s2", new Student("2", "张三2"));
		oc.put("s3", new Student("3", "张三3"));
		
		Teacher teacher = new Teacher("1","小李");
		// 将teacher设置为非根对象,如果在设置了根对象以后,再为根对象设置无效,会以之前第一次设置的为根对象
		oc.setRoot(teacher); 
		
		//取值.
		String tname = (String)Ognl.getValue("tname", oc, teacher);
		Student stu = (Student)Ognl.getValue("#s1", oc, teacher);
		String s1sname = (String)Ognl.getValue("#s1.sname", oc, teacher);
		System.out.println("tname: "+tname+" stu: "+stu+"  s1.sname: "+s1sname);
}

 

 

猜你喜欢

转载自blog.csdn.net/qq_41097820/article/details/83963821