OGNL表达式和EL表达式

来源:互联网 发布:python 技术指标 编辑:程序博客网 时间:2024/04/30 15:07

struts2标签中只能用OGNL表达式只能是EL表达式???  MARK一下,有待研究……


以下内容转自:http://blog.sina.com.cn/s/blog_7ffb8dd5010149u5.html

OGNL表达式的基本语法和用法

 (2012-11-03 01:15:26)
首先我们一起来看一下OGNL中的#%$符号
关于OGNL各种用法总结参看:http://blog.163.com/seara520@126/blog/static/72069304201032081730286/

一.OGNL中的#%$符号

      #%$符号在OGNL表达式中经常出现,而这三种符号也是开发者不容易掌握和理解的部分。在这里我们简单介绍它们的相应用途。

1#符号的三种用法

   1访问非根对象属性,例如示例中的#session.msg表达式,由于Struts 2中值栈被视为根对象,所以访问其他非根对象时,需要加#前缀。实际上,#相当于ActionContext. getContext()#session.msg表达式相当于ActionContext.getContext().getSession(). getAttribute("msg") 

   2用于过滤和投影(projecting)集合,如示例中的persons.{?#this.age>20}

   3 用来构造Map,例如示例中的#{'foo1':'bar1', 'foo2':'bar2'}

2%符号

      %符号的用途是在标志的属性为字符串类型时,计算OGNL表达式的值。如下面的代码所示:

<h3>构造Map</h3>

    <s:set name="foobar" value="#{'foo1':'bar1', 'foo2':'bar2'}" />

    <p>The value of key "foo1" is <s:property value="#foobar['foo1']" /></p>

    <p>不使用%:<s:url value="#foobar['foo1']" /></p>

   <p>使用%:<s:url value="%{#foobar['foo1']}" /></p>

运行界面如下所示。

he value of key "foo1" is bar1

不使用%#foobar['foo1']

使用%bar1

3$符号

$符号主要有两个方面的用途。

     1 在国际化资源文件中,引用OGNL表达式,例如国际化资源文件中的代码:reg.agerange=国际化资源信息:年龄必须在${min}${max}之间。

     2 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常用表达式:

 

1. 当使用OGNL调用静态方法的时候,需要按照如下语法编写表达式: 

@package.classname@methodname(parameter) 

2. 对于OGNL来说,java.lang.Math是其的默认类,如果调用java.lang.Math的静态方法时,无需指定类的名字,比如:@@min(4, 10); 

3. 对于OGNL来说,数组与集合是一样的,都是通过下标索引来去访问的。

获取List:<s:property value="testList"/><br>

获取List中的某一个元素(可以使用类似于数组中的下标获取List中的内容):

<s:property value="testList[0]"/><br>

获取Set:<s:property value="testSet"/><br>

获取Set中的某一个元素(Set由于没有顺序,所以不能使用下标获取数据):

<s:property value="testSet[0]"/><br> ×

获取Map:<s:property value="testMap"/><br>

获取Map中所有的键:<s:property value="testMap.keys"/><br>

获取Map中所有的值:<s:property value="testMap.values"/><br>

获取Map中的某一个元素(可以使用类似于数组中的下标获取List中的内容):

<s:property value="testMap['m1']"/><br>

获取List的大小:<s:property value="testSet.size"/><br>

4. 使用OGNL来处理映射(Map)的语法格式如下所示: 

#{key1value1key2value2key3value3}; 

5. 过滤(filtering):collection.{? expression} 

6. OGNL针对集合提供了一些伪属性(如sizeisEmpty),让我们可以通过属性的方式来调用方法(本质原因在于集合当中的很多方法并不符合JavaBean的命名规则),但我么你依然还可以通过调用方法来实现与伪属性相同的目的。 

7. 过滤(filtering),获取到集合中的第一个元素:collection.{^ expression} 

8. 过滤(filtering),获取到集合中的最后一个元素:collection.{& expression} 

9. 在使用过滤操作时,我们通常都会使用#this,该表达式用于代表当前正在迭代的集合中的对象(联想增强的for循环) 

10. 投影(projection):collection.{expression} 

11. 过滤与投影之间的差别:类比于数据库中的表,过滤是取行的操作,而投影是取列的操作。 具体举例如下:

利用选择获取List中成绩及格的对象:<s:property value="stus.{?#this.grade>=60}"/><br>

利用选择获取List中成绩及格的对象的username:

<s:property value="stus.{?#this.grade>=60}.{username}"/><br>

利用选择获取List中成绩及格的第一个对象的username:

<s:property value="stus.{?#this.grade>=60}.{username}[0]"/><br>

利用选择获取List中成绩及格的第一个对象的username:

<s:property value="stus.{^#this.grade>=60}.{username}"/><br>

利用选择获取List中成绩及格的最后一个对象的username:

<s:property value="stus.{$#this.grade>=60}.{username}"/><br>

利用选择获取List中成绩及格的第一个对象然后求大小:

<s:property value="stus.{^#this.grade>=600}.{username}.size"/><br>

12. Struts2中,根对象就是ValueStack。在Struts2的任何流程当中,ValueStack中的最顶层对象一定是Action对象。 

13parameters#parameters.username 

request, #request.username 

session, #session.username 

application, #application.username 

attr, #attr.username 

以上几个对象叫做命名对象。 

14访问静态方法或是静态成员变量的改进。 

@vs@method 

15关于Struts2标签库属性值的%#号的关系: 

1如果标签的属性值是OGNL表达式,那么无需加上%{}。 

2如果标签的属性值是字符串类型,那么在字符串当中凡是出现的%{}都会被解析成OGNL表达式,解析完毕后再与其他的字符串进行拼接构造出最后的字符串值。 

3我们可以在所有的属性值上加%{},这样如果该属性值是OGNL表达式,那么标签处理类就会将%{}忽略掉。 

最后一起用代码说话,简单的看一下ognl操作的示例:

1)上下文环境中使用OGNL

public static void main(String[] args)
    {
       
        Map<String , Object> context = new HashMap<String , Object>();

        Person person1 = new Person();
        person1.setName("zhangsan");
      
        Person person2 = new Person();
        person2.setName("lisi");

        Person person3 = new Person();
        person3.setName("wangwu");

       
        Person person4 = new Person();
        person4.setName("zhaoliu");

       
        context.put("person1", person1);
        context.put("person2", person2);
        context.put("person3", person3);

        try
        {
           
            Object value = Ognl.getValue("name", context, person2);
            System.out.println("ognl expression \"name\" evaluation is : " + value);

           
            Object value2 = Ognl.getValue("#person2.name", context, person2);
            System.out.println("ognl expression \"#person2.name\" evaluation is : " + value2);

           
            Object value3 = Ognl.getValue("#person1.name", context, person2);
            System.out.println("ognl expression \"#person1.name\" evaluation is : " + value3);

           
            Object value4 = Ognl.getValue("name", context, person4);
            System.out.println("ognl expression \"name\" evaluation is : " + value4);

           
            Object value5 = Ognl.getValue("#person4.name", context, person4);
            System.out.println("ognl expression \"person4.name\" evaluation is : " + value5);

           
            // Object value6 = Ognl.getValue("#person4.name", context, person2);
           // System.out.println("ognl expression \"#person4.name\" evaluation is : " + value6);

        }

2使用OGNL调用方法

public static void main(String[] args)
    {
       
        OgnlContext context = new OgnlContext();

        People people1 = new People();
        people1.setName("zhangsan");

        People people2 = new People();
        people2.setName("lisi");

        People people3 = new People();
        people3.setName("wangwu");

        context.put("people1", people1);
        context.put("people2", people2);
        context.put("people3", people3);
      
        context.setRoot(people1);

        try
        {
           
            Object value = Ognl.getValue("name.length()", context, context.getRoot());
            System.out.println("people1 name length is :" + value);
          
            Object upperCase = Ognl.getValue("#people2.name.toUpperCase()", context, context.getRoot());
            System.out.println("people2 name upperCase is :" + upperCase);

            Object invokeWithArgs = Ognl.getValue("name.charAt(5)", context, context.getRoot());
            System.out.println("people1 name.charAt(5) is :" + invokeWithArgs);

           
            Object min = Ognl.getValue("@java.lang.Math@min(4,10)", context, context.getRoot());
            System.out.println("min(4,10) is :" + min);

           
            Object e = Ognl.getValue("@java.lang.Math@E", context, context.getRoot());
            System.out.println("E is :" + e);
        }


3使用OGNL操作集合

public static void main(String[] args) throws Exception
    {
        OgnlContext context = new OgnlContext();
      
        Classroom classroom = new Classroom();
        classroom.getStudents().add("zhangsan");
        classroom.getStudents().add("lisi");
        classroom.getStudents().add("wangwu");
        classroom.getStudents().add("zhaoliu");
        classroom.getStudents().add("qianqi");
      
        Student student = new Student();
        student.getContactWays().put("homeNumber", "110");
        student.getContactWays().put("companyNumber", "119");
        student.getContactWays().put("mobilePhone", "112");
      
        context.put("classroom", classroom);
        context.put("student", student);
        context.setRoot(classroom);

       
        Object collection = Ognl.getValue("students", context, context.getRoot());
        System.out.println("students collection is :" + collection);

       
        Object firstStudent = Ognl.getValue("students[0]", context, context.getRoot());
        System.out.println("first student is : " + firstStudent);

       
        Object size = Ognl.getValue("students.size()", context, context.getRoot());
        System.out.println("students collection size is :" + size);

        System.out.println("--------------------------飘逸的分割线--------------------------");
      
        Object mapCollection = Ognl.getValue("#student.contactWays", context, context.getRoot());
        System.out.println("mapCollection is :" + mapCollection);

        Object firstElement = Ognl.getValue("#student.contactWays['homeNumber']", context, context.getRoot());
        System.out.println("the first element of contactWays is :" + firstElement);

        System.out.println("--------------------------飘逸的分割线--------------------------");

       
        Object createCollection = Ognl.getValue("{'aa','bb','cc','dd'}", context, context.getRoot());
        System.out.println(createCollection);

       
        Object createMapCollection = Ognl.getValue("#{'key1':'value1','key2':'value2'}", context, context.getRoot());
        System.out.println(createMapCollection);

    }
}



以下内容转自:http://elf8848.iteye.com/blog/888997


一、EL简介

1.语法结构 
    ${expression}
2.[]与.运算符 
    EL 提供.和[]两种运算符来存取数据。
    当要存取的属性名称中包含一些特殊字符,如.或?等并非字母或数字的符号,就一定要使用 []。例如:
        ${user.My-Name}应当改为${user["My-Name"] }
    如果要动态取值时,就可以用[]来做,而.无法做到动态取值。例如:
        ${sessionScope.user[data]}中data 是一个变量
3.变量 
    EL存取变量数据的方法很简单,例如:${username}。它的意思是取出某一范围中名称为username的变量。
    因为我们并没有指定哪一个范围的username,所以它会依序从Page、Request、Session、Application范围查找。
    假如途中找到username,就直接回传,不再继续找下去,但是假如全部的范围都没有找到时,就回传null。
    属性范围在EL中的名称
        Page         PageScope
        Request         RequestScope
        Session         SessionScope
        Application     ApplicationScope
        
二、EL隐含对象 
1.与范围有关的隐含对象
 
与范围有关的EL 隐含对象包含以下四个:pageScope、requestScope、sessionScope 和applicationScope;
它们基本上就和JSP的pageContext、request、session和application一样;
在EL中,这四个隐含对象只能用来取得范围属性值,即getAttribute(String name),却不能取得其他相关信息。

例如:我们要取得session中储存一个属性username的值,可以利用下列方法:
    session.getAttribute("username") 取得username的值,
在EL中则使用下列方法
    ${sessionScope.username}

2.与输入有关的隐含对象
 
与输入有关的隐含对象有两个:param和paramValues,它们是EL中比较特别的隐含对象。

例如我们要取得用户的请求参数时,可以利用下列方法:
    request.getParameter(String name)
    request.getParameterValues(String name)
在EL中则可以使用param和paramValues两者来取得数据。
    ${param.name}
    ${paramValues.name}

3.其他隐含对象 

cookie
JSTL并没有提供设定cookie的动作,
例:要取得cookie中有一个设定名称为userCountry的值,可以使用${cookie.userCountry}来取得它。

header和headerValues
header 储存用户浏览器和服务端用来沟通的数据
例:要取得用户浏览器的版本,可以使用${header["User-Agent"]}。
另外在鲜少机会下,有可能同一标头名称拥有不同的值,此时必须改为使用headerValues 来取得这些值。

initParam
initParam取得设定web站点的环境参数(Context)
例:一般的方法String userid = (String)application.getInitParameter("userid");
    可以使用 ${initParam.userid}来取得名称为userid

pageContext
pageContext取得其他有关用户要求或页面的详细信息。
    ${pageContext.request.queryString}         取得请求的参数字符串
    ${pageContext.request.requestURL}         取得请求的URL,但不包括请求之参数字符串
    ${pageContext.request.contextPath}         服务的web application 的名称
    ${pageContext.request.method}           取得HTTP 的方法(GET、POST)
    ${pageContext.request.protocol}         取得使用的协议(HTTP/1.1、HTTP/1.0)
    ${pageContext.request.remoteUser}         取得用户名称
    ${pageContext.request.remoteAddr }         取得用户的IP 地址
    ${pageContext.session.new}             判断session 是否为新的
    ${pageContext.session.id}               取得session 的ID
    ${pageContext.servletContext.serverInfo}   取得主机端的服务信息

三、EL运算符 
1.算术运算符有五个:+、-、*或$、/或div、%或mod
2.关系运算符有六个:==或eq、!=或ne、<或lt、>或gt、<=或le、>=或ge
3.逻辑运算符有三个:&&或and、||或or、!或not
4.其它运算符有三个:Empty运算符、条件运算符、()运算符
最常用的表达式:

为空判断:${empty param.name}

三元运算:${A?B:C}

算数运算:${A*(B+C)} 

四、EL函数(functions)。 
语法:ns:function( arg1, arg2, arg3 …. argN)
其中ns为前置名称(prefix),它必须和taglib 指令的前置名称一置
 
1    EL表达式用${}表示,可用在所有的HTML和JSP标签中 作用是代替JSP页面中复杂的JAVA代码.
        2   EL表达式可操作常量 变量 和隐式对象. 最常用的 隐式对象有${param}和${paramValues}. ${param}表示返回请求参数中单个字符串的值. ${paramValues}表示返回请求参数的一组值.pageScope表示页面范围的变量.requestScope表示请求对象的变量. sessionScope表示会话范围内的变量.applicationScope表示应用范围的变量.
        3   <%@ page isELIgnored="true"%> 表示是否禁用EL语言,TRUE表示禁止.FALSE表示不禁止.JSP2.0中默认的启用EL语言.
        4   EL语言可显示 逻辑表达式如${true and false}结果是false    关系表达式如${5>6} 结果是false     算术表达式如 ${5+5} 结果是10
        5   EL中的变量搜索范围是:page request session application   点运算符(.)和"[ ]"都是表示获取变量的值.区别是[ ]可以显示非词类的变量
 ${uplist[0].lzid == zulist.zname?'selected':'' }



0 0
原创粉丝点击