OGNL是Object-Graph Navigation Language的缩写,它是一种功能强大的表达式语言(Expression Language,简称为EL),通过它简单一致的表达式语法,可以存取对象的任意属性,调用对象的方法,遍历整个对象的结构图,实现字段类型转化等功能。它使用相同的表达式去存取对象的属性。
下面讲述OGNL在struts2中的运用:
首先给出两个实体类:
(1)Emp.java
package com.study.struts2.yy; public class Emp { private int age = 8; public Emp(){ } public Emp(int age){ this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "I am 8 years old"; } public String sayHello(){ return "hello"; } }
package com.study.struts2.yy; public class Department { private Emp emp; public Department() { } public Emp getEmp() { return emp; } public void setEmp(Emp emp) { this.emp = emp; } @Override public String toString() { return emp.getAge() + ""; } }(3)配置文件
<struts> <constant name="struts.devMode" value="true" /> <package name="ognl" extends="struts-default" namespace="/actions"> <action name="ognl" class="com.study.struts2.yy.OgnlAction"> <result name="success">/ognl.jsp</result> </action> </package> </struts>
(4)OgnlAction.java
package com.study.struts2.yy; import com.opensymphony.xwork2.ActionSupport; public class OgnlAction extends ActionSupport { private String username; private String password; //添加对象 Emp emp; //添加另一个变量 Department department; public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } public Emp getEmp() { return emp; } public void setEmp(Emp emp) { this.emp = emp; } public 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; } @Override public String execute() throws Exception { return SUCCESS; } }
<a href="<%=basePath %>/actions/ognl?username=yy&password=pp"> ognl</a>
a、访问值栈中的action的普通属性:
<s:property value="username"/>b、访问值栈中对象的普通属性(get set方法)
<s:property value="emp.age"/> | <s:property value="emp['age']"/> | <s:property value="emp[\"age\"]"/>
注意:当前Emp类在Action中没有new,所以需要在地址栏传递emp.age=12等
c、访问值栈中对象的普通属性(get set方法)
<s:property value="department.emp.age"/>方法同b,需要传递department.emp.age的值
<s:property value="password.length()"/>e、访问值栈中对象的普通方法:
public String test(){ return "test"; }进行访问:
<s:property value="test()" />f、访问静态方法
首先在Emp.java中添加一静态方法:
public static String getEmpAge(){ return "8"; }进行访问:
<s:property value="@com.study.struts2.yy.Emp.@getEmpAge()"/>但是,此时访问不到,需要在struts.xml中添加如下:
<constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>g、访问静态属性
首先在Emp.java中添加一静态属性:
public static String str ="aaa";
进行访问:
<s:property value="@com.study.struts2.yy.Emp@str"/>