struts2框架學習筆記5:OGNL表達式
阿新 • • 發佈:2018-02-22
closed 在一起 放置 nbsp lap src list 對象 pan
OGNL取值範圍分兩部分,root、Context兩部分
可以放置任何對象作為ROOT,CONTEXT中必須是Map鍵值對
示例:
準備工作:
public void fun1() throws Exception { // 準備ONGLContext // 準備Root User rootUser = new User("tom", 18); // 準備Context Map<String, User> context = new HashMap<String, User>(); context.put("user1", new User("jack", 18)); context.put("user2", new User("rose", 22)); OgnlContext oc = new OgnlContext(); // 將rootUser作為root部分 oc.setRoot(rootUser); // 將context這個Map作為Context部分 oc.setValues(context); // 書寫OGNL Ognl.getValue("", oc, oc.getRoot());//在""中書寫OGNL表達式即可 }
User類:
package bean; public class User { private String name; private Integer age; public User() { super(); // TODO Auto-generated constructor stub } public User(String name, Integer age) { super(); this.name = name;View Codethis.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
語法:
從root中取出對象:
// 取出root中user對象的name屬性 String name = (String) Ognl.getValue("name", oc, oc.getRoot()); Integer age = (Integer) Ognl.getValue("age", oc, oc.getRoot());
從Context中取出對象:
// 取出context中鍵為user1對象的name屬性 String name1 = (String) Ognl.getValue("#user1.name", oc, oc.getRoot()); String name2 = (String) Ognl.getValue("#user2.name", oc, oc.getRoot()); Integer age = (Integer) Ognl.getValue("#user2.age", oc, oc.getRoot());
為屬性賦值:
// 將root中的user對象的name屬性賦值 Ognl.getValue("name=‘jerry‘", oc, oc.getRoot());
給context賦值:
String name2 = (String) Ognl.getValue("#user1.name=‘張三‘", oc, oc.getRoot());
調用對象的方法:
// 調用root中user對象的setName方法 Ognl.getValue("setName(‘張三‘)", oc, oc.getRoot()); String name1 = (String) Ognl.getValue("getName()", oc, oc.getRoot()); String name2 = (String) Ognl.getValue("#user1.setName(‘lucy‘),#user1.getName()", oc, oc.getRoot());
(註意:可以將兩條語句寫在一起,逗號分隔,返回值是最後一個語句)
調用靜態方法:
Double pi = (Double) Ognl.getValue("@java.lang.Math@PI", oc,oc.getRoot());
創建對象:
// 創建list對象 Integer size = (Integer) Ognl.getValue("{‘tom‘,‘jerry‘,‘jack‘,‘rose‘}.size()", oc, oc.getRoot()); String name1 = (String) Ognl.getValue("{‘tom‘,‘jerry‘,‘jack‘,‘rose‘}[0]", oc, oc.getRoot()); String name2 = (String) Ognl.getValue("{‘tom‘,‘jerry‘,‘jack‘,‘rose‘}.get(1)", oc, oc.getRoot()); // 創建Map對象 Integer size2 = (Integer) Ognl.getValue("#{‘name‘:‘tom‘,‘age‘:18}.size()", oc, oc.getRoot()); String name3 = (String) Ognl.getValue("#{‘name‘:‘tom‘,‘age‘:18}[‘name‘]", oc, oc.getRoot()); Integer age = (Integer) Ognl.getValue("#{‘name‘:‘tom‘,‘age‘:18}.get(‘age‘)", oc, oc.getRoot());
struts2框架學習筆記5:OGNL表達式