Struts2 ValueStack & ActionContext & OGNL 关系小结
原生的OGNL三要素:
1.expression 求值表达式——首先会被解析成对象树
2.root object 根对象——默认的操作对象
3.context OGNL执行环境——OGNL执行的上下文环境
OGNL context是一个Map结构,ognl.OgnlContext类implements Map接口,root对象也在context里面,并且做这一个特殊的对象处理,具体表现为对root 对象的操作不需要加#指示符号(并且加上了#一定取不到root对象里面的值)。
在Struts2中使用ValueStack、ActionContext、ServletContext、request、session等
Ognl从根中取属性, 如果没有则抛异常,
从其他上下文中取属性, 如果没有, 不抛异常,返回为null
import org.junit.Test; public class OgnlTest { @Test public void test1() { OgnlContext context = new OgnlContext(); context.put("name", "zhangsan"); context.put("age", 100); Person person = new Person(); person.setName("wan"); context.put("person", person); Person root = new Person(); root.setName("root"); try { //不带#号, 找root根的属性 System.out.println(Ognl.getValue("name", context, root)); //不带#号,找root根的属性,找不到, 则抛异常ognl.NoSuchPropertyException: com.ognl.Person.person1 // System.out.println(Ognl.getValue("person1", context, root)); System.out.println(Ognl.getValue("#name", context, root)); System.out.println(Ognl.getValue("#person", context, root)); //不存在的属性, =null System.out.println(Ognl.getValue("#person1", context, root)); System.out.println(Ognl.getValue("#person.name", context, root)); //从"hello world"的根里面找name属性, 找不到抛异常 System.out.println(Ognl.getValue("name", context, "hello world")); } catch (OgnlException e) { e.printStackTrace(); } } }