源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

在Java的Struts框架中ONGL表达式的基础使用入门

  • 时间:2020-04-10 06:31 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:在Java的Struts框架中ONGL表达式的基础使用入门
[b]首先了解下OGNL的概念: [/b]OGNL是Object-Graph Navigation Language的缩写,全称为对象图导航语言,是一种功能强大的表达式语言,它通过简单一致的语法,可以任意存取对象的属性或者调用对象的方法,能够遍历整个对象的结构图,实现对象属性类型的转换等功能。 此外,还得先需弄懂OGNL的一些知识: 1.OGNL表达式的计算是围绕OGNL上下文进行的。 OGNL上下文实际上就是一个Map对象,由ognl.OgnlContext类表示。它里面可以存放很多个JavaBean对象。它有一个上下文根对象。 上下文中的根对象可以直接使用名来访问或直接使用它的属性名访问它的属性值。否则要加前缀“#key”。 2.Struts2的标签库都是使用OGNL表达式来访问ActionContext中的对象数据的。如:<s:propertyvalue="xxx"/>。 3.Struts2将ActionContext设置为OGNL上下文,并将值栈作为OGNL的根对象放置到ActionContext中。 4.值栈(ValueStack) : 可以在值栈中放入、删除、查询对象。访问值栈中的对象不用“#”。 Struts2总是把当前Action实例放置在栈顶。所以在OGNL中引用Action中的属性也可以省略“#”。 5.调用ActionContext的put(key,value)放入的数据,需要使用#访问。 [b]OGNL中重要的3个符号:#、%、$: [/b]#、%和$符号在OGNL表达式中经常出现,而这三种符号也是开发者不容易掌握和理解的部分,需要时间的积累才渐渐弄清楚…… [b]1.#符号 [/b]#符号的用途一般有三种。 访问非根对象属性,例如#session.msg表达式,由于Struts 2中值栈被视为根对象,所以访问其他非根对象时,需要加#前缀。实际上,#相当于ActionContext. getContext();#session.msg表达式相当于ActionContext.getContext().getSession(). getAttribute("msg") 。 用于过滤和投影(projecting)集合,如persons.{?#this.age>25},persons.{?#this.name=='pla1'}.{age}[0]。 用来构造Map,例如示例中的#{'foo1':'bar1', 'foo2':'bar2'}。 [b]2.%符号 [/b]%符号的用途是在标志的属性为字符串类型时,计算OGNL表达式的值,这个类似js中的eval,很暴力。 [b]3.$符号 [/b]$符号主要有两个方面的用途。 在国际化资源文件中,引用OGNL表达式,例如国际化资源文件中的代码:reg.agerange=国际化资源信息:年龄必须在${min}同${max}之间。 在Struts 2框架的配置文件中引用OGNL表达式,例如:
<validators>  
  <field name="intb">  
      <field-validator type="int">  
      <param name="min">10</param>  
      <param name="max">100</param>  
      <message>BAction-test校验:数字必须为${min}为${max}之间!</message>  
    </field-validator>  
  </field>  
</validators> 
  示例:第一个OGNL程序
public class OGNL1 
{ 
  public static void main(String[] args) 
  { 
    /* 创建一个Person对象 */ 
    Person person = new Person(); 
    person.setName("zhangsan"); 
     
    try 
    { 
      /* 从person对象中获取name属性的值 */ 
      Object value = Ognl.getValue("name", person); 
 
      System.out.println(value); 
    } 
    catch (OgnlException e) 
    { 
      e.printStackTrace(); 
    } 
  } 
} 
 
class Person 
{ 
  private String name; 
 
  public String getName() 
  { 
    return name; 
  } 
 
  public void setName(String name) 
  { 
    this.name = name; 
  } 
} 
控制台输出:
zhangsan
可以看到我们正确的取得了person对象的name属性值,该getValue声明如下:
public static <T> T getValue(String expression,Object root)throws OgnlException 
 
Convenience method that combines calls to parseExpression and getValue.  
 
Parameters: 
expression - the OGNL expression to be parsed 
root - the root object for the OGNL expression  
Returns: 
the result of evaluating the expression 
OGNL会根据表达式从根对象(root)中提取值。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部