什么是ognl
1.1 OGNL的全称是Object Graph Navigation Language(对象图导航语言),它是一种强大的表达式语言
1.2 OgnlContext(ongl上下文)其实就是Map (教室、老师、学生)
OgnlContext=根对象(1)+非根对象(N)
非根对象要通过"#key"访问,根对象可以省略"#key"
注1:context:英文原意上下文,环境/容器
重点:
1、一个上下文中只有一个根对象
2、取根对象的值,只需要直接通过根对象属性即可
3、非根对象取值必须通过指定的上下文容器中的#key.属性去取。
1、ActionContext一次请求创建一次
2、值栈取值从上往下,取到为止,如果已经拿到,不再往下找。
- ValueStack
2.1 值栈
先进后出的数据结构,弹夹 push/pop
2.2 为什么要使用ValueStack作为根对象
放到值栈中的对象都可视为根对象
从小到大
page -> request -> session -> application
ognl逻辑代码
package test;
import ognl.OgnlContext;
import ognl.OgnlException;
public class Demo1 {
/**
* @param args
* @throws OgnlException
*/
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上下文的根对象
/** ********************** 取值操作 *************************** */
// 表达式name将执行e.getName(),因为e对象是根对象(请注意根对象和非根对象表达式的区别)
//取出ognl上下文(容器)中的根元素(员工)的nama属性值
String employeeName = (String) OnglExpression.getValue("name", ctx, e);
System.out.println(employeeName);
// 表达式#manager.name将执行m.getName(),注意:如果访问的不是根对象那么必须在前面加上一个名称空间,例如:#manager.name
//取出ognl上下文中的非根对象的的name值,非根对象取值必须通过指定的上下文容器中的#key.属性去取
String managerName = (String) OnglExpression.getValue("#manager.name",
ctx, e);
System.out.println(managerName);
// 当然根对象也可以使用#employee.name表达式进行访问
employeeName = (String) OnglExpression.getValue("#employee.name", ctx,
e);
System.out.println(employeeName);
/** ********************** 赋值操作 *************************** */
// 往ognl上下文的根对象的name属性赋值
OnglExpression.setValue("name", ctx, e, "小明");
employeeName = (String) OnglExpression.getValue("name", ctx, e);
System.out.println(employeeName);
// 往ognl上下文的非根对象manager的name属性赋值
OnglExpression.setValue("#manager.name", ctx, e, "孙经理");
managerName = (String) OnglExpression.getValue("#manager.name", ctx, e);
System.out.println(managerName);
OnglExpression.setValue("#employee.name", ctx, e, "小芳");
employeeName = (String) OnglExpression.getValue("name", ctx, e);
System.out.println(employeeName);
}
}