【OGNL】

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

2.使用OGNL:

package com.zking.struts_base2.web;

import com.zking.struts_base1.test.Employee;
import com.zking.struts_base1.test.Manager;

import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;

public class test {
	public static void main(String[] args) {
		Employee e = new Employee();
		e.setName("小李");

		Manager m = new Manager();
		m.setName("张经理");

		// 创建ognl上下文,而ognl上下文实际上就是一个Map对象
		OgnlContext ctx = new OgnlContext();

		// 将员工和经理放到OGNL上下文当中去
		ctx.put("employee", e);
		ctx.put("manager", m);
		ctx.setRoot(e);// 设置OGNL上下文的根对象(一个上下文中只有一个根对象).
		
		/** ********************** 取值操作 *************************** */
		//1.取根对象的值,只需要直接通过根对象属性即可
		try {
			String  employeeName= (String) Ognl.getValue("name", ctx, e);
			System.out.println(employeeName);
		} catch (OgnlException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		//2.非根对象取值必须通过指定的上下文容器中的#key.属性去取。(当然根对象也可以使这种方式进行访问)
		try {
			String managerName= (String) Ognl.getValue("#manager.name",ctx, e);
			System.out.println(managerName);
		} catch (OgnlException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		/** ********************** 赋值操作 *************************** */
		
		try {
			Ognl.setValue("name", ctx, e, "小明");
			String  employeeName= (String) Ognl.getValue("name", ctx, e);
			System.out.println(employeeName);
		} catch (OgnlException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try {
			Ognl.setValue("#manager.name", ctx, e, "孙经理");
			String managerName= (String) Ognl.getValue("#manager.name",ctx, e);
			System.out.println(managerName);
		} catch (OgnlException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	
	}

}

3.划重点:
    1、一个上下文中只有一个根对象
    2、取跟对象的值,只需要直接通过根对象属性即可
    3、非根对象取值必须通过指定的上下文容器中的#key.属性去取。

猜你喜欢

转载自blog.csdn.net/qq_40979551/article/details/83019821