zoukankan      html  css  js  c++  java
  • [JavaEE] 深入理解Struts2的ognl标签

    OGNL是Object-Graph Navigation Language的缩写,全称为对象图导航语言,是一种功能强大的表达式语言,它通过简单一致的语法,可以任意存取对象的属性或者调用对象的方法,能够遍历整个对象的结构图,实现对象属性类型的转换等功能。
    此外,还得先需弄懂OGNL的一些知识:

    1.OGNL表达式的计算是围绕OGNL上下文进行的。
    OGNL上下文实际上就是一个Map对象,由ognl.OgnlContext类表示。它里面可以存放很多个JavaBean对象。它有一个上下文根对象。
    上下文中的根对象可以直接使用名来访问或直接使用它的属性名访问它的属性值。否则要加前缀“#key”。

    2.Struts2的标签库都是使用OGNL表达式来访问ActionContext中的对象数据的。如:<s:propertyvalue="xxx"/>。

    3.Struts2将ActionContext设置为OGNL上下文,并将值栈作为OGNL的根对象放置到ActionContext中。

    4.值栈(ValueStack) :
    可以在值栈中放入、删除、查询对象。访问值栈中的对象不用“#”。
    Struts2总是把当前Action实例放置在栈顶。所以在OGNL中引用Action中的属性也可以省略“#”。

    5.调用ActionContext的put(key,value)放入的数据,需要使用#访问。

    package com.tjcyjd.test.action;     
         
    import java.util.Date;     
    import java.util.LinkedList;     
    import java.util.List;     
         
    import javax.servlet.http.HttpServletRequest;     
         
    import org.apache.struts2.ServletActionContext;     
    import org.apache.struts2.convention.annotation.Action;     
    import org.apache.struts2.convention.annotation.Namespace;     
    import org.apache.struts2.convention.annotation.ParentPackage;     
    import org.apache.struts2.convention.annotation.Result;     
    import org.apache.struts2.convention.annotation.Results;     
    import org.springframework.stereotype.Controller;     
         
    import com.opensymphony.xwork2.ActionContext;     
    import com.opensymphony.xwork2.ActionSupport;     
         
    @Controller     
    @Namespace("/test")     
    @ParentPackage("struts-default")     
    @Results( { @Result(name = "success", location = "/other_test/showognl.jsp"),     
            @Result(name = "fail", location = "/bbs/admin_login.jsp"),     
            @Result(name = "input", location = "/bbs/admin_login.jsp") })     
    public class OgnlAction extends ActionSupport {     
        private static final long serialVersionUID = -1494290883433357310L;     
        private List<Person> persons;     
         
        @Action("ognlTest")     
        public String ognlTest() throws Exception {     
            // 获得ActionContext实例,以便访问Servlet API     
            ActionContext ctx = ActionContext.getContext();     
            // 存入application     
            ctx.getApplication().put("msg", "application信息");     
            // 保存session     
            ctx.getSession().put("msg", "seesion信息");     
            // 保存request信息     
            HttpServletRequest request = ServletActionContext.getRequest();     
            request.setAttribute("msg", "request信息");     
            // 为persons赋值     
            persons = new LinkedList<Person>();     
            Person person1 = new Person();     
            person1.setName("pla1");     
            person1.setAge(26);     
            person1.setBirthday(new Date());     
            persons.add(person1);     
         
            Person person2 = new Person();     
            person2.setName("pla2");     
            person2.setAge(36);     
            person2.setBirthday(new Date());     
            persons.add(person2);     
         
            Person person3 = new Person();     
            person3.setName("pla3");     
            person3.setAge(16);     
            person3.setBirthday(new Date());     
            persons.add(person3);     
         
            return SUCCESS;     
         
        }     
         
        public List<Person> getPersons() {     
            return persons;     
        }     
         
        public void setPersons(List<Person> persons) {     
            this.persons = persons;     
        }     
    } 

    jsp页面showognl.jsp

    <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>       
           
    <%@ taglib prefix="s" uri="/struts-tags" %>       
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/ xhtml1/DTD/xhtml1-transitional.dtd">       
           
    <html xmlns="http://www.w3.org/1999/xhtml">       
           
    <head>       
           
        <title>Struts2 OGNL 演示</title>       
           
    </head>       
           
    <body>           
           
        <h3>访问OGNL上下文和Action上下文</h3>       
           
        <!-使用OGNL访问属性值-->       
           
        <p>parameters: <s:property value="#parameters.msg" /></p>       
           
        <p>request.msg: <s:property value="#request.msg" /></p>       
           
        <p>session.msg: <s:property value="#session.msg" /></p>       
           
        <p>application.msg: <s:property value="#application.msg" /></p>       
           
        <p>attr.msg: <s:property value="#attr.msg" /></p>       
           
        <hr />       
           
        <h3>用于过滤和投影(projecting)集合</h3>       
           
        <p>年龄大于20</p>       
           
        <ul>       
           
        <!-判断年龄-->       
           
            <s:iterator value="persons.{?#this.age>20}">       
           
                <li><s:property value="name" /> - 年龄:<s:property value="age" /></li>       
           
            </s:iterator>       
           
        </ul>       
           
        <p>姓名为pla1的年龄: <s:property value="persons.{?#this.name=='pla1'}.{age}[0]"/></p>       
           
        <hr />       
           
        <h3>构造Map</h3>       
           
        <s:set name="foobar" value="#{'foo1':'bar1', 'foo2':'bar2'}" />       
           
        <p>The value of key "foo1" is <s:property value="#foobar['foo1']" /></p>       
             
        <hr />      
             
        <h4>%符号的用法</h4>       
           
        <s:set name="foobar" value="#{'foo1':'bar1', 'foo2':'bar2'}" />       
           
        <p>The value of key "foo1" is <s:property value="#foobar['foo1']" /></p>       
           
        <p>不使用%:<s:url value="#foobar['foo1']" /></p>       
           
        <p>使用%:<s:url value="%{#foobar['foo1']}" /></p>       
           
        <hr />     
            <%       
                request.setAttribute("req", "request scope");       
                request.getSession().setAttribute("sess", "session scope");       
                request.getSession().getServletContext().setAttribute("app",       
                        "aplication scope");       
            %>       
            1.通过ognl表达式获取 属性范围中的值       
            <br>       
            <s:property value="#request.req" />       
            <br />       
            <s:property value="#session.sess" />       
            <br />       
            <s:property value="#application.app" />       
            <br />       
            <hr>       
           
           2.通过<span style="background-color: #fafafa;">ognl表达式创建list 集合 ,并且遍历出集合中的值       
            <br>       
            <s:set name="list" value="{'eeeee','ddddd','ccccc','bbbbb','aaaaa'}"></s:set>       
            <s:iterator value="#list" var="o">       
                <!-- ${o }<br/> -->       
                <s:property />       
                <br />       
            </s:iterator>       
            <br />       
            <hr>       
           
           3.通过ognl表达式创建Map 集合 ,并且遍历出集合中的值       
            <br>       
            <s:set name="map"       
                value="#{'1':'eeeee','2':'ddddd','3':'ccccc','4':'bbbbb','5':'aaaaa'}"></s:set>       
            <s:iterator value="#map" var="o">       
                <!--      ${o.key }->${o.value }<br/>   -->       
                <!-- <s:property value="#o.key"/>-><s:property value="#o.value"/><br/>   -->       
                <s:property value="key" />-><s:property value="value" />       
                <br />       
            </s:iterator>       
            <br />       
            <hr>       
          4.通过ognl表达式 进行逻辑判断       
            <br>       
            <s:if test="'aa' in {'aaa','bbb'}">       
                aa 在 集合{'aaa','bbb'}中;       
            </s:if>       
            <s:else>       
                aa 不在 集合{'aaa','bbb'}中;       
            </s:else>       
            <br />       
            <s:if test="#request.req not in #list">       
                    不 在 集合list中;       
            </s:if>       
            <s:else>       
                 在 集合list中;       
            </s:else>       
            <br />       
            <hr>       
                 
           5.通过ognl表达式 的投影功能进行数据筛选       
            <br>       
            <s:set name="list1" value="{1,2,3,4,5}"></s:set>       
            <s:iterator value="#list1.{?#this>2}" var="o">       
                <!-- #list.{?#this>2}:在list1集合迭代的时候,从中筛选出当前迭代对象>2的集合进行显示 -->       
                ${o }<br />       
            </s:iterator>       
            <br />       
            <hr>       
           6.通过ognl表达式 访问某个类的静态方法和值       
            <br>       
            <s:property value="@java.lang.Math@floor(32.56)" />       
           
            <s:property value="@com.rao.struts2.action.OGNL1Action@aa" />       
            <br />       
            <br />       
            <hr>       
          7.ognl表达式 迭代标签 详细       
            <br>       
            <s:set name="list2"       
                value="{'aa','bb','cc','dd','ee','ff','gg','hh','ii','jj'}"></s:set>       
            <table border="1">       
                <tr>       
                    <td>索引 </td>       
                    <td></td>       
                    <td>奇?</td>       
                    <td> 偶?</td>       
                    <td>首?</td>       
                    <td> 尾?</td>       
                    <td>当前迭代数量</td>       
                </tr>       
                <s:iterator value="#list2" var="o" status="s">       
                    <tr bgcolor="<s:if test="#s.even">pink</s:if>">       
                        <td>       
                            <s:property value="#s.getIndex()" />       
                        </td>       
                        <td>       
                            <s:property />       
                        </td>       
                        <td>       
                            <s:if test="#s.odd">Y</s:if>       
                            <s:else>N</s:else>       
                        </td>       
                        <td>       
                            <s:if test="#s.even">Y</s:if>       
                            <s:else>N</s:else>       
                        </td>       
                        <td>       
                            <s:if test="#s.first">Y</s:if>       
                            <s:else>N</s:else>       
                        </td>       
                        <td>       
                            <s:if test="#s.isLast()">Y</s:if>       
                            <s:else>N</s:else>       
                        </td>       
                        <td>       
                        <s:property value="#s.getCount()"/>       
                    </td>       
                    </tr>       
                </s:iterator>       
            </table>       
            <br>       
            <hr>            
                 
                 
           8.ognl表达式:  if/else if/else 详细<br>       
            <% request.setAttribute("aa",0); %>       
            <s:if test="#request.aa>=0 && #request.aa<=4">       
                    在0-4之间;       
            </s:if>       
            <s:elseif test="#request.aa>=4 && #request.aa<=8">       
                    在4-8之间;       
            </s:elseif>       
            <s:else>       
                 大于8;       
            </s:else>       
            <br>       
            <hr>       
        9.ognl表达式: url 详细<br>       
            <% request.setAttribute("aa","sss"); %>       
            <s:url action="testAction" namespace="/aa/bb">       
                <s:param name="aa" value="#request.aa"></s:param>       
                <s:param name="id">100</s:param>       
            </s:url>       
            <br/>       
            <s:set name="myurl" value="'http://www.baidu.com'"></s:set>       
            value以字符处理:   <s:url value="#myurl"></s:url><br>       
            value明确指定以ognl表达式处理:    <s:url value="%{#myurl}"></s:url>       
            <br>       
            <hr>       
        10.ognl表达式: checkboxlist 详细<br>       
            1> .list 生成;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br>       
            name:checkboxlist的名字<br>       
            list:checkboxlist要显示的列表<br>       
            value:checkboxlist默认被选中的选项,checkedchecked=checked<br>       
            <s:checkboxlist name="checkbox1" list="{'上网','看书','爬山','游泳','唱歌'}" value="{'上网','看书'}" ></s:checkboxlist>       
            <br>       
             以上生成代码:<br>       
            <xmp>       
                <input type="checkbox" name="checkbox1" value="上网" id="checkbox1-1" checked="checked"/>       
                <label for="checkbox1-1" class="checkboxLabel">上网</label>       
                <input type="checkbox" name="checkbox1" value="看书" id="checkbox1-2" checked="checked"/>       
                <label for="checkbox1-2" class="checkboxLabel">看书</label>       
                <input type="checkbox" name="checkbox1" value="爬山" id="checkbox1-3"/>       
                <label for="checkbox1-3" class="checkboxLabel">爬山</label>       
                <input type="checkbox" name="checkbox1" value="游泳" id="checkbox1-4"/>       
                <label for="checkbox1-4" class="checkboxLabel">游泳</label>       
                <input type="checkbox" name="checkbox1" value="唱歌" id="checkbox1-5"/>       
                <label for="checkbox1-5" class="checkboxLabel">唱歌</label>"       
            </xmp>       
            2> .Map 生成;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br>       
            name:checkboxlist的名字<br>       
            list:checkboxlist要显示的列表<br>       
            listKey:checkbox 的value的值<br>       
            listValue:checkbox 的lablel(显示的值)<br>       
            value:checkboxlist默认被选中的选项,checkedchecked=checked<br>       
            <s:checkboxlist name="checkbox2" list="#{1:'上网',2:'看书',3:'爬山',4:'游泳',5:'唱歌'}" listKey="key" listValue="value" value="{1,2,5}" ></s:checkboxlist>       
            <br>       
                           以上生成代码:<br>       
            <xmp>       
                <input type="checkbox" name="checkbox2" value="1" id="checkbox2-1" checked="checked"/>       
                <label for="checkbox2-1" class="checkboxLabel">上网</label>       
                <input type="checkbox" name="checkbox2" value="2" id="checkbox2-2" checked="checked"/>       
                <label for="checkbox2-2" class="checkboxLabel">看书</label>       
                <input type="checkbox" name="checkbox2" value="3" id="checkbox2-3"/>       
                <label for="checkbox2-3" class="checkboxLabel">爬山</label>       
                <input type="checkbox" name="checkbox2" value="4" id="checkbox2-4"/>       
                <label for="checkbox2-4" class="checkboxLabel">游泳</label>       
                <input type="checkbox" name="checkbox2" value="5" id="checkbox2-5" checked="checked"/>       
                <label for="checkbox2-5" class="checkboxLabel">唱歌</label>       
            </xmp>       
            <hr>       
    </body>       
    </html> 

    --------------------------------------

    欢迎您,进入 我系程序猿 的cnBlog博客。

    你不能改变你的过去,但你可以让你的未来变得更美好。一旦时间浪费了,生命就浪费了。

    You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted.

    --------------------------------------

    分享到QQ空间  

  • 相关阅读:
    BZOJ1187 [HNOI2007]神奇游乐园(插头dp)
    BZOJ4926 皮皮妖的递推
    BZOJ3684 大朋友和多叉树(多项式相关计算)
    BZOJ4574 [Zjoi2016]线段树
    杜教筛进阶+洲阁筛讲解+SPOJ divcnt3
    从几场模拟考试看一类分块算法
    bzoj3142 luogu3228 HNOI2013 数列
    luogu3244 bzoj4011 HNOI2015 落忆枫音
    codeforces 286E Ladies' Shop
    BZOJ4825 单旋
  • 原文地址:https://www.cnblogs.com/jqmtony/p/3947936.html
Copyright © 2011-2022 走看看