Basic grammar and usage of OGNL

Original address: https://blog.csdn.net/qq_29663071/article/details/51005100


Basic syntax and basic usage of OGNL expressions
1. #, % and $ signs in OGNL

#, %, and $ symbols appear frequently in OGNL expressions, and these three symbols are also parts that are not easy for developers to grasp and understand. Here we briefly introduce their corresponding uses.

1. Three uses of the # symbol

1) To access non-root object properties, such as the #session.msg expression in the example, since the value stack in Struts 2 is regarded as a root object, you need to add # prefix when accessing other non-root objects. In fact, # is equivalent to ActionContext.getContext(); #session.msg expressions are equivalent to ActionContext.getContext().getSession().getAttribute("msg").

2) For filtering and projecting collections, such as persons.{?#this.age>20} in the example.

3) Used to construct a Map, such as #{'foo1':'bar1', 'foo2':'bar2'} in the example.

2. %symbol

The purpose of the % symbol is to evaluate the value of the OGNL expression when the attribute of the flag is of type string. As shown in the code below:

<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>

The running interface is shown below.

The value of key “foo1” is bar1

Without %: #foobar['foo1']

use %:bar1

3. $ sign

The $ symbol serves two main purposes.

1) In the internationalized resource file, refer to the OGNL expression, such as the code in the internationalized resource file: reg.agerange=Internationalized resource information: age must be in m i n same between {max}.

2) Reference the OGNL expression in the configuration file of the Struts 2 framework, as shown in the following code snippet:

<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>  

two. Let's take a look at the common expressions of OGNL :

  1. When using OGNL to call a static method , you need to write the expression according to the following syntax:
    @package.classname@methodname(parameter)

  2. For OGNL, java.lang.Math is its default class . If you call the static method of java.lang.Math, you do not need to specify the class name, for example: @@min(4, 10);

  3. For OGNL, arrays are the same as sets, they are accessed by subscript indexing .
    Get List:
    <s:property value="testList"/><br>

    Get an element in the List (you can use the subscript similar to the array to get the content in the List):
    <s:property value="testList[0]"/><br>

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

    Get an element in the Set (Because the Set has no order, you cannot use subscripts to get data):

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

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

    Get all the keys in the Map:
    <s:property value="testMap.keys"/><br>

    Get all the values ​​in the Map:
    <s:property value="testMap.values"/><br>

    Get an element in the Map (you can use the subscript similar to the array to get the content in the List):

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

    Get the size of the List:
    <s:property value="testSet.size"/><br>

  4. The syntax format for using OGNL to process maps is as follows:
    {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'};

  5. Filtering : collection.{? expression}

  6. OGNL provides some pseudo attributes (such as size, isEmpty) for collections, so that we can call methods through attributes (the essential reason is that many methods in collections do not conform to the JavaBean naming rules), but you can still By calling a method to achieve the same purpose as a pseudo-property.

  7. Filtering to get the first element in the collection: collection.{^ expression}

  8. Filtering to get the last element in the collection: collection.{& expression}

  9. When using filter operations, we usually use #this, which is used to represent the object in the collection currently being iterated (associative enhanced for loop)

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

  11. The difference between filtering and projection: analogous to the table in the database, filtering is the operation of fetching rows, while projection is the operation of fetching columns. The specific example is as follows:
    Use selection to obtain the objects with passing grades in the List:
    <s:property value="stus.{?#this.grade>=60}"/><br>

    Use selection to get the username of the object with passing grades in the List:
    <s:property value="stus.{?#this.grade>=60}.{username}"/><br>

    Use selection to get the username of the first object in the list with a passing grade:

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

    Use selection to get the username of the first object in the list with a passing grade:
    <s:property value="stus.{^#this.grade>=60}.{username}"/><br>

    Use select to get the username of the last object in the list that passed the grade:
    <s:property value="stus.{$#this.grade>=60}.{username}"/><br>

    Use selection to get the first object in the list with passing grades and then find the size:
    <s:property value="stus.{^#this.grade>=600}.{username}.size"/><br>

12. In Struts2, the root object is the ValueStack. In any process of Struts2, the top-level object in the ValueStack must be the Action object.
13.
parameters, #parameters.username

request, #request.username

session, #session.username

application, #application.username

attr, #attr.username

The above objects are called "named objects"
14. Improvements in accessing static methods or static member variables.

@vs@method
15. About the relationship between % and # in the attribute value of Struts2 tag library :

1). If the attribute value of the tag is an OGNL expression, then there is no need to add %{}.

2). If the attribute value of the tag is a string type , then all occurrences of %{} in the string will be parsed into an OGNL expression. After parsing, it will be spliced ​​with other strings to construct the final string value. .

3). We can add %{} to all attribute values, so that if the attribute value is an OGNL expression, the tag processing class will ignore %{} .

Finally, let’s talk with the code together, simply look at the example of ognl operation:
1) Use OGNL in the context

public static void main(String[] args)  
    {  
        /* 创建一个上下文Context对象,它是用保存多个对象一个环境 对象*/  
        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");  

        /* person4不放入到上下文环境中*/  
        Person person4 = new Person();  
        person4.setName("zhaoliu");  

        /* 将person1、person2、person3添加到环境中(上下文中)*/  
        context.put("person1", person1);  
        context.put("person2", person2);  
        context.put("person3", person3);  

        try  
        {  
            /* 获取根对象的"name"属性值*/  
            Object value = Ognl.getValue("name", context, person2);  
            System.out.println("ognl expression \"name\" evaluation is : " + value);  

            /* 获取根对象的"name"属性值*/  
            Object value2 = Ognl.getValue("#person2.name", context, person2);  
            System.out.println("ognl expression \"#person2.name\" evaluation is : " + value2);  

            /* 获取person1对象的"name"属性值*/  
            Object value3 = Ognl.getValue("#person1.name", context, person2);  
            System.out.println("ognl expression \"#person1.name\" evaluation is : " + value3);  

            /* 将person4指定为root对象,获取person4对象的"name"属性,注意person4对象不在上下文中*/  
            Object value4 = Ognl.getValue("name", context, person4);  
            System.out.println("ognl expression \"name\" evaluation is : " + value4);  

            /* 将person4指定为root对象,获取person4对象的"name"属性,注意person4对象不在上下文中*/  
            Object value5 = Ognl.getValue("#person4.name", context, person4);  
            System.out.println("ognl expression \"person4.name\" evaluation is : " + value5);  

            /* 获取person4对象的"name"属性,注意person4对象不在上下文中*/  
            // Object value6 = Ognl.getValue("#person4.name", context, person2);  
           // System.out.println("ognl expression \"#person4.name\" evaluation is : " + value6);  

        }  

2) Call the method using OGNL

public static void main(String[] args)  
    {  
        /* OGNL提供的一个上下文类,它实现了Map接口*/  
        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) Manipulate collections using 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);  

        /* 获得classroom的students集合*/  
        Object collection = Ognl.getValue("students", context, context.getRoot());  
        System.out.println("students collection is :" + collection);  

        /* 获得classroom的students集合*/  
        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);  

        /* 创建Map集合*/  
        Object createMapCollection = Ognl.getValue("#{'key1':'value1','key2':'value2'}", context, context.getRoot());  
        System.out.println(createMapCollection);  

    }  
}  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324879800&siteId=291194637