一、OGNL
1、OGNL的全称是Object Graph Navigation Language(对象图导航语言),它是一种强大的表达式语言
2、OgnlContext(ongl上下文)其实就是Map (教室、老师、学生)
OgnlContext=根对象(1)+非根对象(N)非根对象要通过"#key"访问,根对象可以省略"#key"
重点:
①、一个上下文中只有一个根对象
②、取跟对象的值,只需要直接通过根对象属性即可
③、非根对象取值必须通过指定的上下文容器中的#key.属性去取。
二、 ValueStack
1、值栈的使用
先进后出的数据结构,弹夹 push/pop
public static void main1(String[] args) {
// 栈:表示一个先进后出的数据结构
ActionContext ac = ActionContext.getContext();
System.out.println(ac);
ValueStack vs = ac.getValueStack();
// push方法把项压入栈顶
vs.push(new Employee("zs", 22));
vs.push(new Employee("ls", 22));
vs.push(new Employee("ww", 22));
// pop方法移除栈顶对象并作为此函数的值返回该对象
Employee e = (Employee) vs.pop();
System.out.println(e.getName());
e = (Employee) vs.pop();
System.out.println(e.getName());
e = (Employee) vs.pop();
System.out.println(e.getName());
//ww/ls/zs
}
public String execute() {
main1(null);
return "success";
}
2、用于模拟struts2的值栈计算过程
public static void main2(String[] args) {
ActionContext ac = ActionContext.getContext();
ValueStack vs = ac.getValueStack();
vs.push(new Employee("张雇员", 2000));// 1
vs.push(new Student("小明同学", "s001"));// 0
System.out.println(vs.findValue("name"));
System.out.println(vs.findValue("salary"));
//小明、salary=2000
}
public String execute() {
main2(null);
return "success";
}
3、为什么要使用ValueStack作为根对象
放到值栈中的对象都可视为根对象
从小到大(作用域)
page -> request -> session -> application
重点:
①、ActionContext一次请求创建一次
②、值栈取值从上往下,取到为止,如果已经拿到,不再往下找。
三、伪代码
ActionContext ac = ActionContext.getContext();//保证同一请求中只创建一个上下文
request
session
application
parameters
ValueStack(root)
向ValueStack压栈
push(XxxAction)//helloAction
push(ModelDirver.getModel())//model不为null user
Map<String,String[]> map = request.getParamterMap(); 压action代码详解
//参数名==OGNL表达式
{"userName":"aaa","uname":"bbb","upwd":"ccc","age":"22"}
setValue("userName", ac, vs, "aaa");
setValue("uname", ac, vs, "bbb");
setValue("upwd", ac, vs, "ccc");
setValue("age", ac, vs, "22");
四、struts2中传递数据
可以使用作用域,但更多的是利用ValueStack或ActionContext