OGNL表达式学习

来源:互联网 发布:linux 双网卡 同网段 编辑:程序博客网 时间:2024/06/07 22:14

OGNL表达式学习

  博主虽然有用过OGNL表达式来处理struts2传到后台的数据,但是时日一长,没有及时的复习,加上也没有系统的学习过,所以在这里记录一下,希望不仅能帮助自己还能帮助别人!

import java.util.HashMap;import java.util.Map;import com.future.ognl.domain.Person;import ognl.Ognl;import ognl.OgnlException;public class OgnlTest {    public static void main(String[] args) {        /*创建一个上下文context对象,*/        Map<String, Object> context = new HashMap<String, Object>();        Person person1 = new Person();        person1.setName("person1");        Person person2 = new Person();        person2.setName("person2");        Person person3 = new Person();        person3.setName("person3");        /*注意:没有把 person3 放入到上下文中*/        context.put("person1", person1);        context.put("person2", person2);        try {            /*若不指定查找对象,OGNL会从根对象开始查找*/            /*获取根对象的 name 属性值*/            String value = (String) Ognl.getValue("name",context, person1);            System.out.println("person1's name is : " + value);            /*获取根对象的 name 属性值*/            String person2Name = (String)Ognl.getValue("#person2.name", context, person2);            System.out.println("person2's name is : " + person2Name);            /*将 person3 指定为根对象,获取 person3 的 name 属性值*/            String person3Name = (String)Ognl.getValue("name", context, person3);            System.out.println("person3's name is : " + person3Name);            /*使用#指定查找对象,则从指定的对象中查找,指定的对象必须在上下文中!!             * 否则会抛出异常:ognl.OgnlException: source is null for getProperty(null, "name")*/            /*String person3Name2 = (String)Ognl.getValue("#person3.name", context, person3);            System.out.println("person3's name is : " + person3Name2);*/            /*调用成员方法*/            int lengthOfPerson1Name = (int) Ognl.getValue("name.length()", context, person1);            System.out.println("the length of person1'name is : " + lengthOfPerson1Name);            String person1NameToUpper = (String)Ognl.getValue("#person1.name.toUpperCase()", context, person1);            System.out.pre(oupper of person1'name is : " + person1Nam```    // TODO Auto-generated catch block            e.printStackTrace();        }    }
0 0
原创粉丝点击