OGNL, a simple struts 2-specific expression, do you express it? (10)

Source: Internet
Author: User
Tags format definition ole

ognl object Graphic Language (object map navigation language), ognl is an open source project where readers can visit their official site Span lang= "en-US" >www.ognl.org for source code and related information. ognl is a powerful el (expression Language , expression language), you can access the properties in the java object through a simple expression.

OGNL first applied in the webwork project, and also the default expression language for Struts 2 frame view, it can be said that theOGNL expression is Struts 2 one of the characteristics of the framework.

8.1.3 an Example of using OGNL

The following article is a simple example to help readers understandOGNLan expression. UseOGNLexpression that needs to bewww.ognl.orgWeb site to download aOgnl.jarplug-in package, copy the file to theClasspathpath. Create a composite type, such as code8.1as shown.




Code 8.1 defining a composite type

Package ch8;

Import Java.util.Date;

// Team Class

public class Team {

    // Team Name

private String teamname;

    // Define team staff attributes

private person person;

    // Number of teams

private int personnum;

Getter and setter methods for// attributes

public String getteamname () {

return teamname;

    }

public void Setteamname (String teamname) {

this.teamname = teamname;

    }

Public Person Getperson () {

return person;

    }

public void Setperson (person person) {

This.person = person;

    }

public int getpersonnum () {

return personnum;

    }

public void setpersonnum (int personnum) {

this.personnum = personnum;

    }

}

// Defining people classes

Class Person {

    // name

private String name;

    // Age

private int age;

    // date of birth of person

private Date birthday;

Getter and setter methods for// attributes

public String getName () {

return name;

    }

public void SetName (String name) {

this.name = name;

    }

public int getage () {

return age;

    }

public void setage (int age) {

this.age = age;

    }

public Date getbirthday () {

return birthday;

    }

public void Setbirthday (Date birthday) {

this.birthday = birthday;

    }

}

Code 8.1 The content shown defines two composite types: the Team ( Team ) and personnel ( Person ) type. Use An example of the OGNL expression, as shown in code 8.2 .




Code 8.2 Use OGNL Expression Examples

Package ch8;

Import Java.util.HashMap;

Import Java.util.Map;

Import Ognl. OGNL;

Import Ognl. Ognlexception;

public class Testognl {

public static void Main (string[] args) {

/ / define a Map Object

Map m = new HashMap ();

/ / define a team Object

Team team1 = new Team ();

Team1.setteamname (" team 1");

/ / define a person Object

Person person1 = new person ();

person1.setname ("Pla1");

/ / add team element

Team1.setperson (Person1);

/ / define a team Object

Team team2 = new Team ();

Team2.setteamname (" team 2");

/ / define a person Object

Person person2 = new person ();

person2.setname ("PLA2");

/ / add team element

Team2.setperson (Person2);

/ / add Map element

m.put ("team1", team1);

m.put ("team2", team2);

try {

System.out.println (Ognl.getvalue ("Team1.teamname", m));

System.out.println (Ognl.getvalue ("Team2.person.name", m));

System.out.println (Ognl.getvalue ("Teamname", team2));

System.out.println (Ognl.getvalue ("Person.name", team2));

catch (ognlexception e) {

        }

    }

}

Code 8.2 The content shown here defines a Map Nested properties of the type, as shown in 8.1 as shown.

< c17>

Figure 8.1 nested attribute sketch

Running the example, the controller displays the following information:

Team 1

Pla2

Team 2

Pla2

★ description ★

OGNL You can use very simple expressions to access multi-tier nested properties, providing a powerful tool for developers.

The OGNL of 8.2 Struts 2

ognl struts 2 struts 2

8.2.1 Struts 2 of the OGNL An expression

Standard ofOGNLwill set a root object (Rootobject). Hypothetical use criteriaOGNLexpression to evaluate without using theStruts 2of theOGNLexpression), ifOGNLContext (Ognlcontext Maptype) has two objects:Fooobject, inOgnlcontexta name inFoo;Barobject, inOgnlcontexta name inBar. At the same timeFooobject is set to the root object (Root). Then use the followingOGNLEvaluation of Expressions:

// return Foo.getblah ()

#foo. blah

// return Bar.getblah ()

#bar. blah

// return Foo.getblah () , because Foo as the root object

Blah

★ description ★

Use OGNL is very simple, if the object to be accessed is not the root object, as in the example Bar object, you need to use a namespace that uses the # "to identify, such as" #bar If you access a root object, you can directly access the properties of the root object without specifying a namespace.

in theStruts 2in the frame, the value stack (Value Stack) isOGNLroot object that has two object instances in the stack of values:MansandAnimal, both of these object instances have anameProperties,Animalhave aspeciesProperties,Manshave aSalaryproperty, assuming thatAnimalat the top of the value stack,Mansin theAnimallater, the following code snippet will help the reader to better understandOGNLAn expression:

// Call animal.getspecies ()

Species

// Call man.getsalary ()

Salary

// Call Animal.getname () , because Animal at the top of the value stack

Name

The last line of sample code returns theAnimal.getname ()returns a value that returns theAnimalof thenameproperty, becauseAnimalis the top element of the value stack,OGNLwill be searched from the top element, so it will returnAnimalof thenameThe property value. If you want to getMansof thenamevalue, you need the following code:

Man.name

Struts 2 allows indexes to be used in the value stack, as shown in the sample code:

[0].name // call animal.getname ()

[1].name // call man.getname ()

★ description ★

Using an index, instead of getting the specified element directly, you search from the specified index location.

Struts 2 in the OGNL Context is Actioncontext , as shown in Figure 8.2 as shown.

Figure 8.2 Struts 2 of the OGNL Context structure schematic

Span ' Times New Roman '; Mso-hansi-font-family: ' Times Roman ' ">★ description ★

Figure 8.2 just stating Struts 2 of the OGNL Context structure, actually Context also contains other objects.

because the value stack is Struts 2 in OGNL root object, you can access the properties in the value stack directly from the following code, if the user needs to access the objects in the value stack:

// gets the value in the stack Foo Property

${foo}

If you access other Context object, because it is not the root object , you need to add # prefix.

? application object: for access to ServletContext or #application [' UserName '] servlet getattribute (" Username ")

session object: Used to access httpsession the # Session.username

? Requestobjects: Used to accessHttpServletRequestProperties (attribute) ofMap, such as#request. UserNameor#request [' UserName '], which is equivalent to callingRequest.getattribute ("UserName").

? parameters object: for access to http The request parameters of the or #parameters [' UserName '] request.getparameter ("username")

attr Span ' Times New Roman '; Mso-hansi-font-family: ' Times Roman ' "> object: Used to press Page-request-session-application

8.2.2   OGNL Collection operations

when you need a collection element (for example , List object or Map object), you can use the OGNL An expression associated with a collection in the

You can use the following code to directly generate a List objects:

{E1,e2,e3 ...}

theOGNLexpression, you directly generate aListobject that theListobject contains the3elements:E1,E2andE3. If you need more elements, you can define multiple elements in such a format, separating multiple elements with commas.

The following code can directly generate a Map objects:

#{key1:value1,key2:value2,...}

Map the collection object of the type, using the Key-value format definition, each Key-value the element is identified by a colon and separated by commas between multiple elements.

for collection types,OGNLAn expression can use the inand not intwo element symbols. Among them, inAn expression is used to determine whether an element is in the specified collection object; not indetermines whether an element is not in the specified collection object, such as code8.3as shown.




Code 8.3 Use OGNL Set operator

<s:if test= "' foo ' in {' foo '", ' Bar '} ' >

Muhahaha

</s:if>

<s:else>

Boo

</s:else>

<s:if test= "' foo '" ' Not in ' ' foo ', ' ' Bar '} ' >

Muhahaha

</s:if>

<s:else>

Boo

</s:else>

except for the in and not in ognl 3

? ? : Get all logical elements.

? ^ : Get the first element that conforms to logic.

? $ : Get the last element that conforms to logic.

For example, code:

Person.relatives. {#this. Gender = = ' Male '}

This code can get Span lang= "en-US" >person the male relatievs collection.

8.2.3   Lambda expression

OGNL Support for Basic Lambda expression syntax, using the Lambda expression syntax, which can be used in an OGNL Some simple functions are used in the For example:

Fibonacci:

If n==0 return 0;

ElseIf n==1 return 1;

else return fib (n-2) +fib (n-1);

FIB (0) = 0

FIB (1) = 1

FIB (11) = 89

developers can use Lambda expression Syntax:

<s:property value= "#fib =:[#this ==0? 0: #this ==1? 1: #fib (#this-2) + #fib (#this-1)], #fib (one)"/>







</

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.