一、概念
OGNL表达相当于JSP+Servlet模式中JSTL的地位,但是它的功能要比JSTL强大,在学习OGNL表达式时,你需要忘掉JSTL.OGNL能够访问系统中OgnlContext中的对象, OgnlContext对象是OGNL表达式的下上文对象,即所有通过OGNL表达式取出的数据都是从上下文对象取出来的, OGNL的上下文环境是一个Map结构,称之为OgnlContext。
要想在JSP页面中使用ONGL,得在页头加上:
<%@taglib prefix="s" uri="/struts-tags" %>
二、用例
Action代码 在各个范围内定义值
ValueStack valueStack=actionContext.getValueStack();//值栈
valueStack.set("name", "张三(valueStack)");
valueStack.set("age", 11);
Map<String,Object> session= actionContext.getSession();
session.put("name", "王五(session)");
session.put("age", 13);
Map<String,Object> application= actionContext.getApplication();
application.put("name", "赵六(application)");
application.put("age", 14);
students= new ArrayList<Student>();
students.add(new Student("老九",13));
students.add(new Student("老十",14));
studentMap = new HashMap<String,Student>();
studentMap.put("goodStudent", new Student("学霸",20));
studentMap.put("badStudent", new Student("学渣",20));
在JSP中设置request的VALUEKEY
<%
request.setAttribute("name", "李四(request)");
request.setAttribute("age", "12");
%>
JSP代码
获取狭义上的值栈数据:<s:property value="name"/>
<s:property value="age"/> <br>
请求参数:<s:property value="#parameters.name"/>
<s:property value="#parameters.age"/><br>
request:<s:property value="#request.name"/>
<s:property value="#request.age"/><br>
session:<s:property value="#session.name"/>
<s:property value="#session.age"/><br>
application:<s:property value="#application.name"/>
<s:property value="#application.age"/><br>
ongl访问javaBean对象:<s:property value="student.name"/>
<s:property value="student.age"/><br>
ongl访问List集合对象:<s:property value="students[0].name"/>
<s:property value="student[0].age"/><br>
<s:property value="students[1].name"/>
<s:property value="student[1].age"/><br>
ongl访问Map集合对象:<s:property value="studentMap['goodStudent'].name"/>
<s:property value="studentMap['goodStudent'].age"/><br>
<s:property value="studentMap['badStudent'].name"/>
<s:property value="studentMap['badStudent'].age"/><br>
三、ONGL访问静态方法
首先在Struts.xml中定义:
<!--ognl获取静态方法 --> <constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>
静态方法:
public class MyStatic {
public static final String str="Java知识分享网";
public static String printUrl(){
//System.out.println("http://www.java1234.com");
return "www.java1234.com";
}
}
页面代码:
<body>
访问静态属性:<s:property value="@com.java1234.common.MyStatic@str"/><!--访问静态成员变量-->
访问静态方法:<s:property value="@com.java1234.common.MyStatic@printUrl()"/><span style="font-family: Arial, Helvetica, sans-serif;"><!--访问静态方法--></span>
</body>