OGNL表达式语言基础ABC

OGNL表达式语言能够帮助我们访问存在于ValueStack和ActionContext中的值.

首先让我们来看看通过OGNL来访问一个String数组的变量.在action类中我们创建一个string数组,代码如下:

package vaannila; public class SampleAction { private String[] sampleArray; { sampleArray = new String[]{"item1","item2","item3"}; } public String execute() { return "success"; } public String[] getSampleArray() { return sampleArray; } public void setSampleArray(String[] sampleArray) { this.sampleArray = sampleArray; } }

这样,在success中就能够通过下面的方式读取这个数组的值:

Array Usage Examples


sampleArray : sampleArray.length : sampleArray[0] : [0].sampleArray : top.sampleArray :

下图就是页面的输出效果:

上面有三种方式能够获取到sampleArray.由于这个sampleArray是在这个stack的top.所以可以通过[0]或者top这个关键字来

直接取到.

下面看看怎么获取到一个ArrayList,在action类中创建一个ArrayList:

package vaannila; import java.util.ArrayList; import java.util.List; public class SampleAction { private List sampleList = new ArrayList(); { sampleList.add("listItem1"); sampleList.add("listItem2"); sampleList.add("listItem3"); } public String execute() { return "success"; } public List getSampleList() { return sampleList; } public void setSampleList(List sampleList) { this.sampleList = sampleList; } }

同样可以通过下面的方式显示这个list:

List Usage Examples


sampleList : sampleList.size : sampleList[0] :

下面再来看看怎么读取一个map类型的数据.通过在action类中创建一个map:

package vaannila; import java.util.HashMap; import java.util.Map; public class SampleAction { private Map sampleMap = new HashMap(); private String carMake; { sampleMap.put(new Integer(1), "one"); sampleMap.put(new Integer(2), "two"); sampleMap.put(new Integer(3), "three"); } public String execute() { return "success"; } public Map getSampleMap() { return sampleMap; } public void setSampleMap(Map sampleMap) { this.sampleMap = sampleMap; } public String getCarMake() { return carMake; } public void setCarMake(String carMake) { this.carMake = carMake; } }

可以通过下面的方式来访问这个map:

Map Usage Examples


sampleMap[1] : sampleMap.size :

当然你可以直接在jsp中声明一个map:

下面来看看怎么访问在action中model对象的属性name.代码如下:

package vaannila; public class SampleAction { private User user = new User(); { user.setName("Eswar"); } public String execute() { return "success"; } public String getQuote() { return "Don't think, just do"; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }

可以通过下面的方式来访问:

user.name :

同样可以在jsp中直接调用action中的一个方法:

quote() :

related link:http://www.dzone.com/tutorials/java/struts-2/struts-2-example/struts-2-ognl-expression-language-example-1.html