ognl:对象导航语言,struts就是一个大的ognl
1.取对象属性
User u=new User("HZP", "z");
Department dep=new Department("yb");
u.setDep(dep);
System.out.println(Ognl.getValue("username", u));
System.out.println(Ognl.getValue("dep.name", u));
u
--id
--nickname
--username
--dep
--name
ogal,通过根来找值
2.取map里的对象的属性
User u=new User("HZP", "梓芃");
Department dep=new Department("易班");
u.setDep(dep);
Role r=new Role("admin");
Map<String, Object> ctx=new HashMap<>();
ctx.put("user", u);
ctx.put("role", r);
try {
System.out.println(Ognl.getValue("username", ctx, u));//表示从u(根)取
System.out.println(Ognl.getValue("#user.username", ctx, u));//表示取maps中的user.username
System.out.println(Ognl.getValue("#root.username", ctx, u));//所有东西有一个最大的根,这根就是一个ctx,里面放一个root,root就是u
} catch (OgnlException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
u
--id
--nickname
--username
--dep
--name
maps
--user
--role
3.取list里对象的属性
List<User> users=new ArrayList<>();
users.add(new User("HZP1", "p1"));
users.add(new User("HZP2", "p2"));
try {
System.out.println(Ognl.getValue("#root[0].username", users));
} catch (OgnlException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
map中用 #key.属性,list没有key,只能用 #root[0].username
4.调用对象里的方法
List<User> users=new ArrayList<>();
users.add(new User("HZP1", "p1"));
users.add(new User("HZP2", "p2"));
try {
System.out.println(Ognl.getValue("#root[0].sum(1,3)", users));
System.out.println(Ognl.getValue("get(0).sum(1,3)", users));
User u=new User("H1", "黄1");
System.out.println(Ognl.getValue("hi('你好')", u));
} catch (OgnlException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
#取list里对象可以用#root[0].属性 或者 get(0).属性
注意'你好'要加单引号!