你的位置:首页 > Java教程

[Java教程]ognl表达式初步使用


这是ognl表达式的初步使用,在action中配置好展示的数据。

package test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OgnlAction {
//基本对象
private int id=1;
private String name="zhangsan";
//实体类型
private User user=new User();
//数组和集合
private String[] cityArray=new String[]{"beijing","shanghai","guangzhou"};
private List<String> cityList=new ArrayList<String>();
private Map<String,String> cityMap=new HashMap<String, String>();


public String[] getCityArray() {
return cityArray;
}
public void setCityArray(String[] cityArray) {
this.cityArray = cityArray;
}
public List<String> getCityList() {
return cityList;
}
public void setCityList(List<String> cityList) {
this.cityList = cityList;
}
public Map<String, String> getCityMap() {
return cityMap;
}
public void setCityMap(Map<String, String> cityMap) {
this.cityMap = cityMap;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}

public String Ognl1(){
//初始化实体
user.setName("wangwu");
user.setPassword("123456");
//初始化集合
cityList.add("qingdao");
cityList.add("shenzhen");
cityList.add("guangzhou");
//初始化Map
cityMap.put("beijing","2300人口");
cityMap.put("shanghai","2000人口");
cityMap.put("guangzhou","1800人口");
return "success";
}
}

 

配置完action后,在配置jsp

<%@ page import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
</head>
<body>
<h1>ognl基本属性</h1>
<s:property value="id"/><br>
<s:property value="name"/>
<h1>ognl实体属性</h1>
<s:property value="user.name"/><br>
<s:property value="user.password"/>
<h1>ognl集合数组</h1>
<s:property value="cityArray[0]"/><br>
<s:property value="cityArray[1]"/><br>
<s:property value="cityArray[2]"/><br>
<s:property value="cityList[0]"/><br>
<s:property value="cityList[1]"/><br>
<s:property value="cityList[2]"/><br>
<h1>访问map</h1>
<s:property value="cityMap.beijing"/><br>
<h1>访问时经行计算</h1>
<s:property value="'go to '+cityList[0]"/><br>
<h1>调用方法</h1>
<s:property value="cityArray[2].toUpperCase()"/>
<h1>创建集合</h1>
<s:property value="{'1','2','3'}"/>
<s:property value="{'1','2','3'}.getClass().getName()"/>
<h1>创建map</h1>
<s:property value="#{'1':'a','2':'b'}"/>
<s:property value="#{'1':'a','2':'b'}.getClass().getName()"/>
</body>
</html>