Map<String , Object> context = new HashMap<String , Object>(); Person person1 = new Person(); person1.setName("zhangsan"); Department dep = new Department(); dep.setName("xx"); person1.setDep(dep); Person person2 = new Person(); person2.setName("lisi"); Person person3 = new Person(); person3.setName("wangwu"); context.put("p1", person1); context.put("p2", person2); context.put("p3", person3); oc.put("name", person3); String name=""; try { // name = (String)Ognl.getValue("name", context,person1); // name = (String)Ognl.getValue("dep.name", person1); name = (String)Ognl.getValue("#root.name",context, person1); } catch (OgnlException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(name); } 进入getValue: public static Object getValue(String expression, Map context, Object root) throws OgnlException { return getValue(expression, context, root, null); } public static Object getValue(String expression, Map context, Object root, Class resultType) throws OgnlException { return getValue(parseExpression(expression), context, root, resultType); } public static Object getValue(Object tree, Map context, Object root, Class resultType) throws OgnlException { OgnlContext ognlContext = (OgnlContext)addDefaultContext(root, context); Node node = (Node)tree; Object result; if(node.getAccessor() != null) result = node.getAccessor().get(ognlContext, root); else result = node.getValue(ognlContext, root); if(resultType != null) result = getTypeConverter(context).convertValue(context, root, null, null, result, resultType); return result; } OgnlContext ognlContext = (OgnlContext)addDefaultContext(root, context); public static Map addDefaultContext(Object root, Map context) { return addDefaultContext(root, null, null, null, context); } public static Map addDefaultContext(Object root, ClassResolver classResolver, TypeConverter converter, MemberAccess memberAccess, Map context) { OgnlContext result; if(!(context instanceof OgnlContext)) { result = new OgnlContext(); result.setValues(context); } else { result = (OgnlContext)context; } if(classResolver != null) result.setClassResolver(classResolver); if(converter != null) result.setTypeConverter(converter); if(memberAccess != null) result.setMemberAccess(memberAccess); result.setRoot(root); return result; }
name = (String)Ognl.getValue("#root.name",context, person1);
大概流程是:如果context不是OgnlContext,就新建一个OgnlContext再将此context设置其中
:
result = new OgnlContext(); result.setValues(context);
如果context是OgnlContext,直接转换成OgnlContext,然后设置OgnlContext的root:
result.setRoot(root);