Ognl訪問陣列、List和Map
阿新 • • 發佈:2019-01-24
陣列
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對集合做了特殊處理。