标签:
OGNL
Object graphic Navgation language 对象图形的导航语言
org.zttc.itat.model下面三个class
Department.class
Role.class
User.class
package org.zttc.itat.model; public class User//两个构造函数 { private int id; private String username; private String nickname; private Department dep; //以上成员变量全部都有get和set方法 //method public int sum(int a, int b) { return a + b; } public String hello(String word) { return "hello" + word; } } ---------------------------------------------------------------------------- package org.zttc.itat.model; public class Department { private String name; //get and set } } ----------------------------------------------------------------------------- package org.zttc.itat.model; /** * Created by Melody on 2015/11/7. */ public class Role { private int id; private String name; //构造函数和get set方法 } ----------------------------------------------------------------------------- Test package org.zttc.itat.test; import ognl.Ognl; import ognl.OgnlException; import org.junit.Test; import org.zttc.itat.model.*; import java.util.*; public class TestOngl { @Test public void test01() throws OgnlException { User u = new User(1, "tangseng", "唐僧"); Department dep = new Department("财务处"); u.setDep(dep); //第二个参数是root System.out.println(Ognl.getValue("nickname", u));//唐僧 //从u里面找dep dep里面找name System.out.println(Ognl.getValue("dep.name", u));//财务处 } @Test public void test02() throws OgnlException { Map<String, Object> ctx = new HashMap<String, Object>(); User u = new User(1, "tangseng", "唐僧"); Department dep = new Department("财务处"); u.setDep(dep); Role r = new Role(1, "Admin"); ctx.put("user", u); ctx.put("role", r); //想找根u里面的对象 //没加# 是在root中找 加了#是在ctx中找 System.out.println(Ognl.getValue("username", ctx, u));//唐僧 //想找ctx里面的对象 #user.username是在ctx这个map中找 //ctx是一个map{"user", u} (String, Object) //ActionContext.getContext()是一个map 所以后面也要加# System.out.println(Ognl.getValue("#user.username", ctx, u));//唐僧 System.out.println(Ognl.getValue("#role.name", ctx, u));//Admin //Ogn其实就是一个最大的Context,根的key就是root 所以可以根据#root.***来取 //所有东西有个最大的根context(map)里面有个root里面放的是u System.out.println(Ognl.getValue("#root.username", ctx, u));// } @Test public void test03() throws OgnlException { List<User> users = new ArrayList<User>(); users.add(new User(1, "ts", "唐僧")); users.add(new User(2, "ss", "沙僧")); users.add(new User(3, "bj", "八戒")); users.add(new User(4, "wk", "悟空")); //如果要取list中的元素 需要通过#root[index] 来完成取值 System.out.println(Ognl.getValue("#root[1].nickname", users));//沙僧 //看到没有 ognl还可以完成方法的调用 System.out.println(Ognl.getValue("#root[0].sum(1, 3)", users));//沙僧 //访问了u的hello(Stirng) 方法 注意里面的String要加‘‘ User u = new User(); System.out.println(Ognl.getValue("hello(‘world‘)", u)); //可以通过List(java的集合)中的中get()方法获取某个下标的对象 然后完成导航 System.out.println(Ognl.getValue("get(0).username", users)); /* 沙僧 4 helloworld ts */ } }
标签:
原文地址:http://www.cnblogs.com/taojiatao/p/4945331.html