Struts2-OGNL Expression language

Source: Internet
Author: User

1.OGNL is object-graph Navigation language abbreviation, is a powerful expression language, through its simple and consistent expression syntax, you can access any property of the object, call the method of the object, traverse the whole object's structure diagram, Enables the conversion of field types and other functions. Where OGNL is most used is binding with the Struts2 tag, or you can use the OGNL expression in the configuration file through ${}.



There are several common symbols in the 2.OGNL expression, and the use of these three symbols is described below:

(1). Use of $ in OGNL: The first, you can reference the OGNL expression in an internationalized resource file. Second, you can reference the OGNL expression in the Struts.xml configuration file.

(2). Use of% in OGNL: The purpose of the% sign is to evaluate the value of the OGNL expression when the flag property is a string type.

~ Use%{} to remove the action object stored in the value stack and invoke its method directly.

~ If the action class inherits the Actionsupport class, you can use%{gettext (' key ')} in the page label to obtain internationalized information.

(3). Use of # in OGNL: # in OGNL can remove objects stored in the stack context, accessing OGNL context and action context. #相当于ActionContext. GetContext ().

~ Where there are 5 objects in the context of a stack (attr,request,session,application,parameters):

attr: Used to access its properties in Request>>session>>application Order, #attr. UserName, which is equivalent to reading the UserName attribute sequentially from three ranges until it is found.

Request: A map containing the properties of the current HttpServletRequest, #request. UserName, equivalent to Request.getattribute ("UserName").

Session: A map containing the properties of the current HttpSession, #session. UserName, equivalent to Session.getattribute ("UserName").

Application: A map containing the properties of the currently applied ServletContext, #application. UserName, which is equivalent to Application.getattribute ("UserName").

Parameters: A map containing the parameters of the current HTTP request, #parameters. Id[0], equivalent to Request.getparameter ("id").



3. Gets the property value in the action or the value of the object in the action:

Using the <s:property/> tag, you can get the Username property of the reference type in the user directly in the action. It is also possible to get the value of the Addr property in the reference type address of the user by user.address.addr, such as this layer of layer-by-step access, called navigation, which is called in steps.



4. The normal method inside the object that invokes the action:

The default will put the action into the value stack, while the value stack in the access, do not need the name of the value stack, when we use <s:property value= "User.getvomethod ()"/>, It will automatically find the value stack inside the Action object there is no user object, if found that there is a user object, then it will find the user there is no Getvomethod () method, if found, then call Getvomethod () this method.

The process of actually calling the Getvomethod () method is the same as getting the name and password in the form, all in the value stack to find out if there is a user object, and if so, then find out if there is a property or method in the user.



5. Invoke the static method in the action:

We can use the OGNL expression in the JSP page to invoke the static method in action, and when invoking the static method in the action, the process of invoking the Getvomethod () method of the user object is completely different. At this point, the notation of value is fixed, starting with @, followed by the specific package name, and then @ Plus static methods, such as <s:property value= "@[email protected] ()"/>. In addition, the user object is only a property in Loginaction, this property will automatically put in the value stack, and the value stack call, do not add @ or package name, etc., so the direct User.getvomethod ().



6. Call the static method in the JDK class:

You can use the <s:property value= "@ @floor (46.68)"/> Output floor () execution results, which means that if you do not specify a class in @@ 中 The default is to represent the Java.lang.Math class, most of the time, it will not omit this class, will be written in full, and then add a static method.



7. Pseudo property of a collection: OGNL can refer to some special properties of the collection, which are not javabean patterns, such as size (), length (), and when an expression references these properties, OGNL invokes the appropriate method, which is a pseudo-attribute, such as getting the size of a list, You can use the <s:property value= "testlist.size ()"/>.

Pseudo property of list: Size,isempty,iterator.

Pseudo property of Set: Size,isempty,iterator.

Pseudo attribute of map: size,isempty,keys,values.

Pseudo-attribute of Iterator (iteration): Next,hasnext.

Pseudo-attribute of enumeration (enum): Next,hasnext,nextelement,hasmoreelements.



8. To get the essence of an element in a collection is to call its ToString () method:

The OGNL expression can also directly get the elements in the collection, in fact the ToString () method of the call collection, so we can implement the personalization output by overriding the ToString () method of the collection according to the actual situation, even as it accesses the array directly testlist[2 ] Gets the elements of the collection, but this method applies only to list, not to map. Because the map index is key, not a numeric value, and because the elements of hashset are not sequential, you cannot use subscripts to get a single element.



9. Use projection to get properties: When using a projection to get the Username property of an object in a list, where {} represents a collection, Stus. {UserName} means that all UserName attributes in the Stus are taken out to form a new list.



10. Use the selection to get properties:

The OGNL expression is flexible enough to be able to use selection techniques and projection techniques to get properties, #this代表当前元素, question marks? is to remove all elements that satisfy the condition, the up arrow ^ is the beginning meaning, the dollar sign $ is the end meaning, and the three symbols return the list.



11. Supplement:

(1). When OGNL does not get the value, it does not error, but does not show anything

(2 ). <s:property value= "[0 ] "/> return valuestack All from top to bottom object <s:property value=" [1] "/> returned is valuestack objec

(3).<s:property value= "[0].username"/>returns the value of the member variable username ,assuming there are two actions in the Valuestack , if the first action does not have a Username Variable ,then it will continue looking for a second Action. So under what circumstances will there be two Action in valuestack ? ?     

The answer is configured in struts.xml from an Action via <result type= "Chain" > Jumps to another Action.

(4). <constant name= "struts.ognl.allowStaticMethodAccess" value= "true"/>,in theStruts2.1.6must be set instruts.ognl.allowStaticMethodAccess is true after,To allow access to static methods using OGNL . and in The Struts2.0.11 does not need to be set, you can directly access.





12. Here is an example of how to get the value of a property in an action with an OGNL expression or a property value in an Action object, or how to invoke the common method in the object inside the action and the general method of the Action class:
(1). Create a new STRUTS2 project with the project name STRUTS2_OGNL, first create a new action class that inherits from the Actionsupport class with the following code:
Package Com.gk.action;import Com.gk.bean.cat;import Com.gk.bean.user;import com.opensymphony.xwork2.ActionSupport; public class Ognlaction extends Actionsupport {private string Username;private string password;private user User=new User ( );p rivate cat cat=new Cat ();p ublic String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} Public User GetUser () {return user;} public void SetUser (user user) {this.user = user;} Public Cat Getcat () {return cat;} public void Setcat (cat cat) {this.cat = cat;} Public String Execute () {return SUCCESS;}}


(2). There are several JavaBean classes, respectively, User,cat,dog class, the code is as follows: User.java file code:
Package Com.gk.bean;public class User {private int-age = 8;public User () {}public User (int.) {this.age = age;} public int getage () {return age;} public void Setage (int.) {this.age = age;} @Overridepublic String toString () {return "user" +age;}}

Cat.java File Code:
Package Com.gk.bean;public class Cat {private Dog friend;public dog Getfriend () {return friend;} public void Setfriend (Dog friend) {this.friend = friend;} Public String Miaomiao () {return ' Miaomiao ';}}

Dog.java File Code:
Package Com.gk.bean;public class Dog {private string Name;public Dog () {}public dog (String name) {this.name=name;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String toString () {return "dog" +name;}}

(3). There are two JSP pages, one is index.jsp page, one is the ognl.jsp page, the code is as follows: index.jsp file code:
<%@ page language= "java" import= "java.util.*" pageencoding= "utf-8"%><%string path = Request.getcontextpath () ; String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
The ognl.jsp code is as follows to get the properties of the action through the STRUTS2 tag and the OGNL expression:
<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%><%@ taglib uri= "/struts-tags" prefix= "s" %><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/";%&GT;&L t;! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
(4). Struts.xml is configured as follows:
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE struts public    "-//apache software foundation//dtd struts Configuration 2.0//en"    "/http Struts.apache.org/dtds/struts-2.0.dtd ">      <struts><constant name=" Struts.enable.DynamicMethodInvocation "value=" true "></constant><constant name=" Struts.devmode "value= "True" ></constant><package name= "OGNL" namespace= "/" extends= "Struts-default" ><action name= "Ognl "Class=" ><result>/ognl.jsp</result></action></package>< "Com.gk.action.OgnlAction" /struts>




13. At this point we visit the index.jsp page and the results are as follows:

Click this link:

Look at the content and context of the value stack:

(1). We can see that the parameters username and password are passed through the hyperlink, then the properties of the username and password in the value stack are removed, and then we see the user attribute in the value stack, and we pass the <s:property value= The "User.age"/> gets to 8 because we initialize age to 8 in the user class, instantiate the user object with the user User=new user in the action class, and then output through the ToString method, So the value of the user property in the stack is User8.

(2). We pass <s:property value= "Cat.friend.name"/> Want to get the name of the friend attribute in the Cat object, but not to take it out, is because we did not pass the Cat.friend.name parameter in, if we enter the address:http://localhost:8083/struts2_ognl/ognl?username=u&password=p& CAT.FRIEND.NAME=LC, it can be taken out, and this is how OGNL accesses the contents of the value stack.


(3) If we enter http://localhost:8083/Struts2_OGNL/ognl?username=u&password=p&user.age=90 this address, the age will become 90 years old:


(4). If we remove the parameterless constructor from public User () {} In the User.java file, and then do not instantiate the user class in the code in Ognlaction, the Ognlaction.java file code is as follows:
Package Com.gk.action;import Com.gk.bean.cat;import Com.gk.bean.user;import com.opensymphony.xwork2.ActionSupport; public class Ognlaction extends Actionsupport {private string Username;private string password;private User user;private C At Cat=new Cat ();p ublic String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} Public User GetUser () {return user;} public void SetUser (user user) {this.user = user;} Public Cat Getcat () {return cat;} public void Setcat (cat cat) {this.cat = cat;} Public String Execute () {return SUCCESS;}}

The Use.java file code is modified to:
Package Com.gk.bean;public class User {private int-age = 8;public User (int.) {this.age = age;} public int getage () {return age;} public void Setage (int.) {this.age = age;} @Overridepublic String toString () {return "user" +age;}}

The age content is then found empty in the input http://localhost:8083/Struts2_OGNL/ognl?username=u&password=p.
If we enter the address as: http://localhost:8083/Struts2_OGNL/ognl?username=u&password=p&user.age=23 See if we can pass the value of age 23 in, Found a mistake, this error is instantiated user error, so generally our domain model, that is, the JavaBean object will always provide a non-parametric construction method, otherwise we do not know which class to instantiate.

(5). We can get the Miaomiao () method of the Cat object directly by <s:property value= "Cat.miaomiao ()"/> This tag. If you want to obtain the ordinary method of the Ognlaction class, that is, the action class common method, if there is a return type string in the action class of the Ordinary method mm (), you can directly use the <s:property value= "mm ()"/&GT; This gives you the return value of the common method of the action class.

(6). Why is ognl called object map navigation language? From the above example, accessing the Age property of the user object of the Ognlaction class, you can use User.age to get access to the Miaomiao method of the Cat object in the Ognlaction class, using Cat.miaomiao (), If you want to access the name attribute in the friend object of the Cat object, use cat.friend.name so that you can get the Name property of the dog's friend object, but you must pass in the parameter value.



14. I would like to attach more than two examples, one example is to use OGNL to access static methods and static properties, but last night when writing code to find some warnings and errors, want to write a blog to record, so first write this, the basic practices and instructions are described above. After I have written the access static method and static properties of that article, after attaching the address.


15. The above content is only for everyone to study and reference, thank you!

Struts2-OGNL Expression language

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.