Struts2-lesson3
OGNL表达式
Object Graphic Navigation Language
对象,图,导航,语言
OGNL表达式取值范围
OGNL基本语法
// 准备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(); oc.setRoot(rootUser); oc.setValues(context); // 书写OGNL // 取出root中user对象的name属性 String name = (String) Ognl.getValue("name", oc, oc.getRoot()); Integer age = (Integer) Ognl.getValue("age", oc, oc.getRoot()); // 取出context中键为user1对象的name属性 String name = (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()); String name = (String) Ognl.getValue("name", oc, oc.getRoot()); String name2 = (String) Ognl.getValue("#user1.name='郝强勇',#user1.name",oc, oc.getRoot()); // 调用root中user对象的setName方法 Ognl.getValue("setName('lilei')", oc, oc.getRoot()); String name = (String) Ognl.getValue("getName()", oc, oc.getRoot()); String name2 = (String) Ognl.getValue("#user1.setName('lucy'),#user1.getName()", oc, oc.getRoot()); // 调用静态方法 String name = (String) Ognl.getValue("@cn.itheima.a_ognl.HahaUtils@echo('hello 强勇!')", oc,oc.getRoot()); // Double pi = (Double) Ognl.getValue("@java.lang.Math@PI", oc, // oc.getRoot()); Double pi = (Double) Ognl.getValue("@@PI", oc, oc.getRoot()); // ognl创建对象-list|map // 创建list对象 Integer size = (Integer) Ognl.getValue("{'tom','jerry','jack','rose'}.size()", oc, oc.getRoot()); String name = (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()); /* * System.out.println(size); System.out.println(name); * System.out.println(name2); */ // 创建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());
OGNL与Struts2的结合
(用List可设计一个栈)
查看值栈中的两部分内容
http://localhost:8080/test_struts2/hello/D3Demo1Action.action
Struts2与ognl结合体现
参数接收中
配置文件中
Struts2标签中
http://localhost:8080/test_struts2/form.jsp
http://localhost:8080/test_struts2/hello/D3Demo3Action.action
击石乃有火,不击元无烟!!