首页 > 技术文章 > OGNL表达式

jxbo 2021-03-06 17:13 原文

OGNL表达式(Oritend Graph Navigation Language--对象图导航语言)
是类似于EL表达式的一种对象操作语言,但是比EL表达式要更为强大
EL表达式的弊端:不能随意的调用对象的方法
OGNL表达式不但在Struts2框架中使用,在Mybatis的框架中也会用到
所谓导航就是:对象.属性/对象.方法/对象.对象.xxx.属性

队列:先进后出
如果取的对象在值栈的顶部(狭义的值栈--是action中定义的全局变量),直接对象.属性

如果取的对象在值栈的底部(广义的值栈--不是action中定义的全局变量,是通过request/session/application传递到页面的对象),需要用#request/session/application.对象.属性

${person.name }
ognl获取对象属性值:<s:property value="person.name"/>

ognl获取对象属性值:<s:property value="#request.person.name"/>
ognl调用对象的方法:<s:property value="#request.person.test1()"/>

默认情况下ognl表达式是不能调用静态方法的(不安全),需要在struts.xml中配置struts.ognl.allowStaticMethodAccess为true

struts.ognl.allowStaticMethodAccess这个常量在struts-core.jar中的default.properties文件中去找

ognl调用对象的静态方法:<s:property value="#request.person.test3('陈')"/>
ognl调用类的静态方法:<s:property value="@com.hr.entity.Person@test3('陈')"/>
ognl调用jdk提供的静态方法:<s:property value="@java.lang.Math@max(1,2)"/>
ognl表达式操作List集合:<s:property value="#request.list[1].fri.name"/>
ognl往list中添加一个元素:<s:property value="#request.list.add(new com.hr.entity.Person('陈',4,new com.hr.entity.Friend('刘')))"/>
ognl表达式操作List集合长度:<s:property value="#request.list.size()"/>
ognl获得list集合中所有person的名字:<s:property value="#request.list.{name}"/>
ognl获得list集合中所有person的friend名字:<s:property value="#request.list.{fri}.{name}"/>
ognl获得list集合中所有person的friend名字:<s:property value="#request.list.{fri.name}"/>

ognl表达式操作map集合:<s:property value="#request.map.keys"/>
ognl表达式操作map集合:<s:property value="#request.map.values"/>
ognl表达式通过key取map的值:<s:property value="#request.map.p3.name"/>
ognl表达式通过key取map的值:<s:property value="#request.map['p3'].name"/>
ognl获取map中所有value的name属性:<s:property value="#request.map.values.{name}"/>

ognl表达式对集合数据的筛选功能:?(取筛选后的所有数据) ^(取筛选后的第一条数据) $(取筛选后的最后一条数据)<br>
<s:property value="#request.list.{?#this.id>1}.{name}"/>
<s:property value="#request.list.{?#this.id>1 and #this.name=='王'}.{name}"/>
<s:property value="#request.list.{?#this.id>1 and #this.name eq '王'}.{name}"/>
<s:property value="#request.list.{?#this.id>1 or #this.name.equals('王')}.{name}"/>
<s:property value="#request.list.{?#this.id>1 and #this.name!='王'}.{name}"/>
<s:property value="#request.list.{?#this.id>1 and #this.name neq '王'}.{name}"/>
<s:property value="#request.list.{?#this.id>1 and !#this.name.equals('王')}.{name}"/>
<s:property value="#request.list.{^#this.id>1}.{name}"/>
<s:property value="#request.list.{$#this.id>1}.{name}"/>

<s:debug></s:debug>

OGNL如何使用:
页面导入struts标签
使用<s:property value="ognl表达式"/>

推荐阅读