【Struts2框架】第三节OGNL表达式-OGNL表达式例子2

1.OGNL静态访问例子

struts.xml:

<struts>
<!--允许静态方法的执行-->
<constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>


<package name="ognl" namespace="/ognl" extends="struts-default">
   <action name="ss" class="cn.edu.hpu.action.IndexAction1">
     <result name="success">/ognl.jsp</result>
   </action>
</package>


</struts>

IndexAction1.java:
package cn.edu.hpu.action;


public class IndexAction1 {
	public String execute(){
		return "success";
	}


}

S.java
package cn.edu.hpu.ognl;

public class S {
	public static String STR="STATIC STRING";
	
	public static String s(){
		return "static method";
	}
}

链接:
访问静态方法:<a href="<%=basePath%>ognl/ss">OGNL6</a><br/>
访问静态属性:<a href="<%=basePath%>ognl/ss">OGNL7</a><br/>

结果界面:
<!--访问方式:@+包名+@+方法名或者属性名-->
<li>访问值栈中静态方法:<s:property value="@cn.edu.hpu.ognl.S@s()"/><br/>
<li>访问值栈中静态属性:<s:property value="@cn.edu.hpu.ognl.S@STR"/><br/>

结果:
访问值栈中静态方法:static method
访问值栈中静态属性:STATIC STRING

常用类的静态方法也可以访问(加两个@)
结果页面:
<li>访问Math类的静态方法:<s:property value="@@max(3,5)"/><br/>

结果:

访问Math类的静态方法:5


2.OGNL访问普通类的构造方法

struts.xml:

<package name="ognl" namespace="/ognl" extends="struts-default">
<action name="dog" class="cn.edu.hpu.ognl.OgnlAction3">
      <result name="success">/ognl.jsp</result>
</action>
</package>

OgnlAction3.java:
package cn.edu.hpu.ognl;

import cn.edu.hpu.mode.Dog;

import com.opensymphony.xwork2.ActionSupport;

public class OgnlAction3 extends ActionSupport{
	private Dog dog;

	public Dog getDog() {
		return dog;
	}

	public void setDog(Dog dog) {
		this.dog = dog;
	}
	
	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return "success";
	}


}

Dog.java:
package cn.edu.hpu.mode;

public class Dog {
	
	private String name;
	
	public Dog(){
		
	}
	
	public Dog(String name){
		super();
		this.name=name;
	}


	public String getName() {
		return name;
	}


	public void setName(String name) {
		this.name = name;
	}


	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "dog:"+name;
	}
}

链接:
访问普通类的构造方法:<a href="<%=basePath%>ognl/dog">OGNL8</a><br/>

结果页面:

<li>访问普通类的构造方法:
<s:property value="new cn.edu.hpu.mode.Dog('tom')"/><br/>

结果:
访问普通类的构造方法:dog:tom

转载请注明出处:http://blog.csdn.net/acmman/article/details/47070019

你可能感兴趣的:(ognl表达式,struts2.0)