数组
package com.xs;
import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;
public class OgnlAarray {
/**
* @param args
* @throws OgnlException
*/
public static void main(String[] args) throws OgnlException {
User user0 = new User();
user0.setPassword("word0");
user0.setUsername("user0");
User user1 = new User();
user1.setPassword("word1");
user1.setUsername("user1");
User[] users = {user0, user1};
OgnlContext context = new OgnlContext();
context.put("users", users);
context.setRoot(users);
System.out.println(Ognl.getValue("length", context, context.getRoot()));
System.out.println(Ognl.getValue("[0].username", context, context.getRoot()));
System.out.println(Ognl.getValue("[1].password", context, context.getRoot()));
}
}
输出:
2
user0
word1
List
package com.xs;
import java.util.ArrayList;
import java.util.List;
import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;
public class OgnlList {
public static void main(String[] args) throws OgnlException{
User user0 = new User();
user0.setPassword("word0");
user0.setUsername("user0");
User user1 = new User();
user1.setPassword("word1");
user1.setUsername("user1");
List<User> list = new ArrayList<User>();
list.add(user0);
list.add(user1);
OgnlContext context = new OgnlContext();
context.put("list", list);
context.setRoot(list);
System.out.println(Ognl.getValue("size", context, context.getRoot()));
System.out.println(Ognl.getValue("[0].username", context, context.getRoot()));
System.out.println(Ognl.getValue("[1].username", context, context.getRoot()));
}
}
输出:
2
user0
user1
Map
package com.xs;
import java.util.HashMap;
import java.util.Map;
import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;
public class OgnlMap {
/**
* @param args
* @throws OgnlException
*/
public static void main(String[] args) throws OgnlException {
User user0 = new User();
user0.setPassword("word0");
user0.setUsername("user0");
User user1 = new User();
user1.setPassword("word1");
user1.setUsername("user1");
Map<String, Object> map = new HashMap<String, Object>();
map.put("u0", user0);
map.put("u1", user1);
OgnlContext context = new OgnlContext();
context.put("map", map);
context.setRoot(map);
System.out.println(Ognl.getValue("size", context, context.getRoot()));
System.out.println(Ognl.getValue("u0.username", context, context.getRoot()));
System.out.println(Ognl.getValue("u1.username", context, context.getRoot()));
}
}
输出:
2
user0
user1
User类:
class User{
private String username;
private String password;
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;
}
}
疑问?
ArrayList和HashMap的字段size不是public的,也没有getter方法(访问size字段的方法为size(),跟字段名一样,对于普通对象是不能这样访问的),但是能通过size访问。
猜测:Ognl对集合做了特殊处理。