struts2 之 ognl

  1. ognl:object graph navigation language:对象导航图语言。
  2. ognl表达式在struts2中有2个作用:表达式语言,类型转换。

  实例如下:

public class OgnlDemo {
    public static void main(String[] args) throws OgnlException {
        //ognl表达式的思想:把数据分为两类:常用的和不常用的。
        //常用的数据一般都是小数据,不常用的数据一般都是大数据。
        //将不常用的数据放在map中
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("school", "sxt");
        map.put("address", "山东菏泽");
        //常用的数据
        User user = new User();
        user.setAge(23);
        user.setName("张三疯");
        Role role = new Role();
        role.setName("管理员");
        user.setRole(role);
        //第一个参数 是ognl表达式  第二参数是ognl上下文(不常用的数据) 第三个参数是ognl的根(常用的数据)
        //表达式的写法:常用的数据直接获取  不常用的数据加#获取
        Object result = Ognl.getValue("#address", map, user);
        System.out.println(result);
        
    }
}

3 . 在struts2中使用ognl表达式来完成数据的设置及获取。并且使用ognl来完成类型转换工作。在struts2中ActionContext对象是ognl的上下文对象,ValueStack是ognl的根对象。ValueStack放的是Action对象的属性。

4.在struts2使用ognl表达式来获取值,需要使用struts2的标签库:

实例如下:

<%@taglib prefix="s" uri="/struts-tags"%>
欢迎<s:property value="username"/>进行系统<br>
欢迎<s:property value="#request.username"/>进行系统<br>

<s:iterator value="list" var="bean">
      <tr>
          <td><s:property value="#bean.id"/></td>
          <td><s:property value="#bean.name"/></td>
          <td><s:property value="#bean.age"/></td>
      </tr>
      </s:iterator>

5. 在struts2使用ognl访问数据的方式总结:

6.使用Struts 标签注意事项:

  (a)使用struts 的标签必须要经过核心过滤器。

  (b)Struts2提供的标签库比较全面,但是不灵活,所以使用比较少。

posted on 2017-04-14 18:01  forever_2h  阅读(136)  评论(0编辑  收藏  举报

导航