Struts使用表達式語言來操作值棧 一

簡介

Struts2默認的表達式語言是OGNL,原因是它相對於其它表達式語言更簡單、強大,最重要的是可以直接操作值棧;
OGNL表達式對值棧的操作,必須依賴Struts2的標籤,所以每個jsp頁面都要引入struts2的標籤庫;
OGNL表達式有三種特殊符號,分別爲#、%、$符號;

“#”號的使用

首先需要在web.xml中配置我好想過濾器
<filter>
  <filter-name>struts</filter-name>
  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>struts</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

在struts.xml中
<package name="struts" extends="struts-default" namespace="/">
    <action name="ognl" class="com.lanou3g.OgnlAction1">
        <result>/result1.jsp</result>
    </action>
</package>

在OgnlAction1類中
public class OgnlAction1 extends ActionSupport{

    @Override
    public String execute() throws Exception {
        // 將數據分別放入request,session,application域中
        ServletActionContext.getRequest().setAttribute("name", "request數據");
        ServletActionContext.getRequest().getSession().setAttribute("name", "session數據");
        ServletActionContext.getServletContext().setAttribute("name", "applicatio數據");
        return SUCCESS;
    }
}

在result1.jsp結果頁面中
<body>
    <h1>通過Ognl表達式獲取request中的數據集</h1>
    <s:property value="#request.name"/> | ${requestScope.name}
    <h1>通過Ognl表達式獲取session中的數據集</h1>           
    <s:property value="#session.name"/> | ${sessionScope.name}
    <h1>通過Ognl表達式獲取application中的數據集</h1>                
    <s:property value="#application.name"/> | ${applicationScope.name}
    <h1>如何獲取page中的數據</h1>
    <%
        pageContext.setAttribute("name", "page數據");
    %>
    <s:property value="#attr.name" /> | ${name }
    <h1>獲取地址欄的信息</h1>
    <s:property value="#parameters.name" />
</body>
結果說明
首先在action類中,將值放入request,session,application域中,之後訪問此action,實現頁面跳轉
然後在頁面中顯示出域中的數據,取數據時,可以用ognl表達式中的#來取,也可以
用el表達式使用$符號來取,由於page域只在當前頁面中有效,而通過地址請求action,再到result1.jsp頁面實際上是經過了請求轉發,
如果在action中給page賦值,經過請求轉發後,result1.jsp中page的值將會消失,所以需要在當前頁面給page域賦值再取出來
當請求路徑中有name屬性時,想取出該路徑中的值,則需要用到parameters.name
結果如圖

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章