OGNL表达式
概述
OGNL是Object-Graph Navigation Language的缩写对象图导航语言!,它是一种功能强大的表达式语言,通过它简单一致的表达式语法,可以存取对象的任意属性,调用对象的方法,遍历整个对象的结构图,实现字段类型转化等功能。它使用相同的表达式去存取对象的属性。如果把表达式看做是一个带有语义的字符串,那么OGNL无疑成为了这个语义字符串与java对象之间沟通的桥梁
OGNL的作用
Struts2默认的表达式语言就是OGNL,它具有如下特点
- 支持对象方法调用
- 支持类静态方法调用和值访问,表达式的格式为 @[类全名(类路径)]@[方法名|值名]
- 支持赋值操作和表达式串联
- 操作集合对象
- 比EL表达式功能更加强大
OGNL的三要素
- 表达式
表达式是整个OGNL的核心,OGNL会根据表达式去对象中取值,所有OGNL操作都是针对表达式解析后进行的,它表明此次OGNL操作要做什么.OGNL支持大量的表达式语法,不仅支持链式对象访问路径,还支持在表达式中进行简单计算 - 根对象(Root)
Root对象可以理解为OGNL的操作对象,表达式还规定了”做什么”,而Root对象则规定了”对谁操作”,OGNL称为对象图导航语言,所谓对象图,即以任意对象为根,通过OHGNL可以访问与这个对象关联的其他对象 - Context对象
实际上这个OGNL的取值还需要一个上下文环境,设置了Root对象,OGNL可以对Root对象进行取值或写值等操作,Root对象所在环境就是OGNL的上下文环境(Context),上下文环境规定了OGNL在哪里进行,上下文环境是一个Map类型的对象,在表达式中访问Context中的对象时需要使用”#”加上对象的名称,这里跟上面的实现不太一致了解即可
public void fun1() throws Exception{
//准备ONGLContext
//准备Root
User rootUser = new User("tom",18);
//准备Context
Map<String,User> context = new HashMap<String,User>();
context.put("user1", new User("jack",18));
context.put("user2", new User("rose",22));
//创建OGNL上下文对象
OgnlContext oc = new OgnlContext();
//将rootUser作为root部分
oc.setRoot(rootUser);
//将context这个Map作为Context部分
oc.setValues(context);
//书写OGNL表达式
Ognl.getValue("", oc, oc.getRoot());
}
使用OGNL准备工作
- 导包
- ognl-3.0.6.jar
语法
- 取出root中的属性值
public void fun2() throws Exception{
//准备ONGLContext
//准备Root
User rootUser = new User("tom",18);
//准备Context
Map<String,User> context = new HashMap<String,User>();
context.put("user1", new User("jack",18));
context.put("user2", new User("rose",22));
OgnlContext oc = new OgnlContext();
oc.setRoot(rootUser);
oc.setValues(context);
//取出root中user对象的name属性
//直接写,默认取栈顶元素
String name = (String) Ognl.getValue("name", oc, oc.getRoot());
Integer age = (Integer) Ognl.getValue("age", oc, oc.getRoot());
System.out.println(name);
System.out.println(age);
}
- 取出context中的属性值
public void fun3() throws Exception{
//准备ONGLContext
//准备Root
User rootUser = new User("tom",18);
//准备Context
Map<String,User> context = new HashMap<String,User>();
context.put("user1", new User("jack",18));
context.put("user2", new User("rose",22));
OgnlContext oc = new OgnlContext();
oc.setRoot(rootUser);
oc.setValues(context);
//书写OGNL
//取出context中键为user1对象的name属性
//需要加 # 因为context是一个map所以采用这种方式
String name = (String) Ognl.getValue("#user1.name", oc, oc.getRoot());
String name2 = (String) Ognl.getValue("#user2.name", oc, oc.getRoot());
Integer age = (Integer) Ognl.getValue("#user2.age", oc, oc.getRoot());
System.out.println(name);
System.out.println(name2);
System.out.println(age);
}
- 为属性赋值
public void fun4() throws Exception{
//准备Root
User rootUser = new User("tom",18);
//准备Context
Map<String,User> context = new HashMap<String,User>();
context.put("user1", new User("jack",18));
context.put("user2", new User("rose",22));
//准备ONGLContext
OgnlContext oc = new OgnlContext();
oc.setRoot(rootUser);
oc.setValues(context);
//书写OGNL
//将root中的user对象的name属性赋值
Ognl.getValue("name='jerry'", oc, oc.getRoot());
String name = (String) Ognl.getValue("name", oc, oc.getRoot());
//将context中的name属性修改
String name2 = (String) Ognl.getValue("#user1.name='郝强勇',#user1.name", oc, oc.getRoot());
System.out.println(name);
System.out.println(name2);
}
- 调用方法
public void fun5() throws Exception{
//准备ONGLContext
//准备Root
User rootUser = new User("tom",18);
//准备Context
Map<String,User> context = new HashMap<String,User>();
context.put("user1", new User("jack",18));
context.put("user2", new User("rose",22));
OgnlContext oc = new OgnlContext();
oc.setRoot(rootUser);
oc.setValues(context);
//书写OGNL
//调用root中user对象的setName方法
Ognl.getValue("setName('lilei')", oc, oc.getRoot());
String name = (String) Ognl.getValue("getName()", oc, oc.getRoot());
String name2 = (String) Ognl.getValue("#user1.setName('lucy'),#user1.getName()", oc, oc.getRoot());
System.out.println(name);
System.out.println(name2);
}
- 调用静态方法
public void fun6() throws Exception{
//准备ONGLContext
//准备Root
User rootUser = new User("tom",18);
//准备Context
Map<String,User> context = new HashMap<String,User>();
context.put("user1", new User("jack",18));
context.put("user2", new User("rose",22));
OgnlContext oc = new OgnlContext();
oc.setRoot(rootUser);
oc.setValues(context);
//书写OGNL
String name = (String) Ognl.getValue("@cn.itheima.a_ognl.HahaUtils@echo('hello 强勇!')", oc, oc.getRoot());
//Double pi = (Double) Ognl.getValue("@java.lang.Math@PI", oc, oc.getRoot());
Double pi = (Double) Ognl.getValue("@@PI", oc, oc.getRoot());
System.out.println(name);
System.out.println(pi);
}
- ognl创建对象-list|map
public void fun7() throws Exception{
//准备ONGLContext
//准备Root
User rootUser = new User("tom",18);
//准备Context
Map<String,User> context = new HashMap<String,User>();
context.put("user1", new User("jack",18));
context.put("user2", new User("rose",22));
OgnlContext oc = new OgnlContext();
oc.setRoot(rootUser);
oc.setValues(context);
//书写OGNL
//创建list对象
Integer size = (Integer) Ognl.getValue("{'tom','jerry','jack','rose'}.size()", oc, oc.getRoot());
String name = (String) Ognl.getValue("{'tom','jerry','jack','rose'}[0]", oc, oc.getRoot());
String name2 = (String) Ognl.getValue("{'tom','jerry','jack','rose'}.get(1)", oc, oc.getRoot());
/*System.out.println(size);
System.out.println(name);
System.out.println(name2);*/
//创建Map对象
Integer size2 = (Integer) Ognl.getValue("#{'name':'tom','age':18}.size()", oc, oc.getRoot());
String name3 = (String) Ognl.getValue("#{'name':'tom','age':18}['name']", oc, oc.getRoot());
Integer age = (Integer) Ognl.getValue("#{'name':'tom','age':18}.get('age')", oc, oc.getRoot());
System.out.println(size2);
System.out.println(name3);
System.out.println(age);
}
OGNL与Struts2的结合
结合原理
ValueStack是Struts2的一个接口,字面意思是值栈,OgnlValueStack是其实现类,客户发起一个请求struts2框架就会创建一个action实例同时创建OgnlValueStack值栈的实例,该实例贯穿整个Action的声明周期,struts2使用OGNL的技术将请求Action的参数封装为对象存储到值栈中,并通过OGNL表达式读取值栈中的对象的属性值
- ValueStack中的两部分
CompoundRoot root;
transient Map<String, Object> context;
* 在创建ActionContext的时候,创建ValueStack对象给ActionContext
* ActionContext中有一个ValueStack的引用,在ValueStack中有一个ActionContext的引用
* ActionContext获取ServletAPI的时候,依赖值栈
* 其实在创建完值栈之后,将值栈的Context部分给了ActionContext
- 栈的原理(先进后出)
public class CompoundRoot extends ArrayList{
public Objetc pop(){
return remove(0);
}
public Object push(object obj){
add(0,obj)
}
....
}
- 访问栈中属性的特点(由上到下)
子啊取栈中属性的时候,会从栈顶开始找属性
找不到会继续向下找
找到就停止
- 查看值栈中两部分数据(使用DEBUG标签)
Root(默认情况下,栈中放置着当前访问的Action对象)
Context
Struts2与ognl结合的体现
参数接收
配置文件
<action name="Demo3Action" class="cn.itheima.d_config.Demo3Action" method="execute" >
<result name="success" type="redirectAction" >
<param name="actionName">Demo1Action</param>
<param name="namespace">/</param>
<!--
如果添加的参数struts"看不懂".就会作为参数附加重定向的路径之后.
如果参数是动态的.可以使用${}包裹ognl表达式.动态取值
-->
<param name="name">${name}</param>
</result>
</action>
struts标签(明天讲)
值栈详解
什么是值栈
1. 问题一:什么是值栈?
\* 值栈就相当于Struts2框架的数据的中转站,向值栈存入一些数据。从值栈中获取到数据。
* ValueStack 是 struts2 提供一个接口,实现类 OgnlValueStack ---- 值栈对象 (OGNL是从值栈中获取数据的 )
* Action是多例的,有一起请求,创建Action实例,创建一个ActionContext对象,代表的是Action的上下文对象,还会创建一个ValueStack对象。
* 每个Action实例都有一个ValueStack对象 (一个请求 对应 一个ValueStack对象 )
* 在其中保存当前Action 对象和其他相关对象
* Struts 框架把 ValueStack 对象保存在名为 “struts.valueStack” 的请求属性中,request中 (值栈对象 是 request一个属性)
* ValueStack vs = (ValueStack)request.getAttribute("struts.valueStack");
值栈的内部结构
2. 问题二 : 值栈的内部结构 ?
* 值栈由两部分组成
> root -- Struts把动作和相关对象压入 ObjectStack 中--List
> context -- Struts把各种各样的映射关系(一些 Map 类型的对象) 压入 ContextMap 中
* Struts会默认把下面这些映射压入ContextMap(context)中
* 注意:request代表的是Map集合的key值,value的值其实也是一个Map集合。
> parameters: 该 Map 中包含当前请求的请求参数 ?name=xxx&password=123
> request: 该 Map 中包含当前 request 对象中的所有属性(request域)
> session: 该 Map 中包含当前 session 对象中的所有属性
> application:该 Map 中包含当前 application 对象中的所有属性
> attr: 该 Map 按如下顺序来检索某个属性: request, session, application
* ValueStack中 存在root属性 (CompoundRoot) 、 context 属性 (OgnlContext )
> CompoundRoot 就是利用ArrayList实现的一个栈
> OgnlContext 就是 Map
* context 对应Map 引入 root对象
> context中还存在 request、 session、application、 attr、 parameters 对象引用
> OGNL表达式访问值栈中的数据
* 访问root中数据时 不需要 #
* 访问 request、 session、application、 attr、 parameters 对象数据 必须写 #
> 操作值栈 默认指 操作 root 元素
值栈的创建和ActionContext对象的关系
* 值栈对象是请求时创建的
* ActionContext是绑定到当前的线程上,那么在每个拦截器或者Action中获取到的ActionContext是同一个。
* ActionContext中存在一个Map集合,该Map集合和ValueStack的context是同一个地址。
* ActionContext中可以获取到ValueStack的引用,以后再开发,使用ActionContext来获取到值栈对象
获取到值栈的对象
* 获得值栈对象 有三种方法
* ValueStack vs1 = (ValueStack) ServletActionContext.getRequest().getAttribute("struts.valueStack");
* ValueStack vs2 = (ValueStack) ServletActionContext.getRequest().getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
* ValueStack vs3 = ActionContext.getContext().getValueStack();
向值栈中保存数据
> valueStack.push(Object obj);
* push方法的底层调用root对象的push方法(把元素添加到0位置)
> valueStack.set(String key, Object obj);
* 源码获取map集合(map有可能是已经存在的,有可能是新创建的),把map集合push到栈顶,再把数据存入到map集合中。
如果栈顶元素是map的话再次传入一个map不创建新的map而是在原来的基础上添加键值对
> 在jsp中 通过 <s:debug /> 查看值栈的内容
从值栈中获取值
6. 问题六: 在JSP中获取值栈的数据
* 总结几个小问题:
> 访问root中数据 不需要#
> 访问context其它对象数据 加 #
> 如果向root中存入对象的话,优先使用push方法。
> 如果向root中存入集合的话,优先要使用set方法。
* 在OgnlContext中获取数据
> 在Action中向域对象中存入值
> request:<s:property value="#request.username"/>
> session:<s:property value="#session.username"/>
> application:<s:property value="#application.username"/>
> attr:<s:property value="#attr.username"/>
> parameters:<s:property value="#parameters.cid"/>
6.1 代码如下
<!--
// vs.push("美美");
//默认从栈中第一个元素开始一直都爱最后一个
<s:property value="[0]"/>
// 获取到栈顶的值(从0开始只去一个)
<s:property value="[0].top"/>
-->
<!--
// 栈顶是map集合,通过key获取值
vs.set("msg", "小凤");
//通过键取值
<s:property value="[0].top.msg"/>
-->
<!--
vs.push(user);
// 栈顶放user对象
//通过属性点的 方式
<s:property value="[0].top.username"/>
<s:property value="[0].top.password"/>
// [0].top 关键字是可以省略的 findValue()
//直接写栈顶对象的属性名
<s:property value="username"/>
-->
<!--
vs.set("user", user);
<s:property value="[0].top.user.username"/>
<s:property value="[0].top.user.password"/>
// 省略关键字
<s:property value="user.username"/>
-->
<!--
// 在ValueStack1Action提供了成员的属性
private User user = new User("小泽","456");
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
User user = new User("小苍","123");
vs.set("user", user);
// 从栈顶开始查找,找user的属性,显示名称 返回的小苍
<s:property value="user.username"/>
// [1].top获取ValueStack1Action [1].top.user返回user对象 [1].top.user.username获取对象的属性名称
<s:property value="[1].top.user.username"/>
-->
<!--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-->
<!--
栈顶是list集合
vs.push(ulist);
<s:property value="[0].top[0].username"/>
<s:property value="[0].top[1].username"/>
-->
<!--
vs.set("ulist", ulist);
<s:property value="ulist[0].username"/>
-->
<!-- 迭代的标签
属性
* value 要迭代的集合,需要从值栈中获取
* var 迭代过程中,遍历的对象
* var编写上,把迭代产生的对象默认压入到context栈中,从context栈取值,加#号,var的取值就是在context中的键
* var不编写,默认把迭代产生的对象压入到root栈中
* list中的User对象会挨个压入到栈中,原先栈顶的元素向下
移动,每次遍历完一个就会弹一个(所以遍历完之后)
for(User user:ulist){}
// 编写var的属性
<s:iterator value="ulist" var="u">
<s:property value="#u.username"/>
<s:property value="#u.password"/>
</s:iterator>
// 没有编写var关键字
<s:iterator value="ulist">
<s:property value="username"/>
<s:property value="password"/>
</s:iterator>
-->
<!--
从context中存值不能使用值栈直接操作而是应该使用这个map集合中的一些map对象(域对象)
从context栈中获取值,加#号
HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("msg", "美美");
request.getSession().setAttribute("msg", "小风");
<s:property value="#request.msg"/>
<s:property value="#session.msg"/>
<s:property value="#parameters.id"/>
<s:property value="#attr.msg"/>
-->
<!-- 在JSP页面上,查看值栈的内部结构 -->
<s:debug></s:debug>
EL表达式也会获取到值栈中的数据
* StrutsPreparedAndExecuteFilter的doFilter代码中 request = prepare.wrapRequest(request);
> 对Request对象进行了包装 ,StrutsRequestWrapper
> 增强了request的 getAttribute
Object attribute = super.getAttribute(s);
if (attribute == null) {
attribute = stack.findValue(s);
}
> 访问request范围的数据时,如果数据找不到,去值栈中找
> request对象 具备访问值栈数据的能力 (查找root的数据)
OGNL中的特殊符号
1. # 符号的用法
* 获得contextMap中的数据
> <s:property value="#request.name"/>
> <s:property value="#session.name"/>
> <s:property value="#application.name"/>
> <s:property value="#attr.name"/>
> <s:property value="#parameters.id"/>
> <s:property value="#parameters.name"/>
* 构建一个map集合
* 例如:
* <s:radio name="sex" list="{'男','女'}"></s:radio>
* <s:radio name="sex" list="#{'0':'男','1':'女'}"></s:radio>
2. % 符号的用法
* 强制字符串解析成OGNL表达式。
> 例如:在request域中存入值,然后在文本框(<s:textfield>)中取值,现在到value上。
> <s:textfield value="%{#request.msg}"/>
* { }中值用''引起来,此时不再是ognl表达式,而是普通的字符串
> 例如:<s:property value="%{'#request.msg'}"/>
3. $ 符号的用法
* 在配置文件中可以使用OGNL表达式,例如:文件下载的配置文件。
<action name="download1" class="cn.itcast.demo2.DownloadAction">
<result name="success" type="stream">
<param name="contentType">${contentType}</param>
<param name="contentDisposition">attachment;filename=${downFilename}</param>
</result>
</action>
request.getAttribute方法的查找顺序
1. 原生的request域
2. ValueStack中的栈(Root)部分
3. 查找ValueStack中的Context(ActionContxt)部分