1. 程式人生 > >Struts2 OGNL使用詳解

Struts2 OGNL使用詳解

OGNL

OGNL ( Object Graph Navigation Language ),物件圖導航語言。這是一種強大的表示式語言,通過它可以非常方便的來操作物件屬性。
在 Struts2 中,OGNL 需要和 Struts2 標籤庫配套來使用。

OGNL context

                               |
                               | -- application
                               |
                               | -- session
                               |

                               | -- value  stack ( root )
context  map  ---- |
                               | -- request
                               |
                               | -- parameters
                               |
                               | -- attr ( searches page, request, session, then application scopes )

                               |
Struts2 框架將 OGNL context 設定為我們的 ActionContext,並將 ValueStack 作為 OGNL 的根物件。而 Action 則置於 ValueStack 的最頂層。
除此之外,Struts2 框架還把代表 application、request、session 物件的 Map 物件也放到 ActionContext 中,使得 Action 與 Servlet API 解耦。
名稱 描述
ValueStack 值棧,作為 OGNL 上下文的根物件。通過 KEY 來訪問,非根物件需要用 #KEY 來訪問
parameters Map 型別,封裝了請求中的所有引數。訪問 #parameters.name 相當於呼叫 HttpServletRequest.getParameter( )
request Map 型別,封裝了 request 物件中的所有屬性。訪問 #request.name 相當於呼叫 HttpServletRequest.getAttribute( )
session Map 型別,封裝了 session 物件中的所有屬性。訪問 #session.name 相當於呼叫 HttpSession.getAttribute( )
application Map 型別,封裝了 application 物件中的所有屬性。訪問 #application.name 相當於呼叫 ServletContext.getAttribute( )
attr Map 型別,依次從 page、request、session、application 物件中檢索屬性的值

OGNL 訪問 Action 中的資料

Action 位於值棧的棧頂位置,而值棧又是 OGNL 的根物件,因此,在 OGNL 表示式中可直接使用屬性名稱來訪問 Action 當中的資料。如:
<s:property value="name" />
實際上,這裡是通過呼叫 Action 當中的 getName( ) 方法來獲取得到資料的,而不管 Action 當中是否有一個名稱為 name 的屬性變數。
因此,如果需要在頁面中獲取得到 Action 當中的資料,你只需要為你的 Action 類編寫 getXX( ) 方法就可以了。

測試環境

package fan.tutorial.model; 

import java.util.Set; 

public  class Person { 

     private String sex; 
     private String name; 
     private IDCard idcard; 
     private Set<Address> addressSet; 
     public  static  final  double VERSION = 1.0; 
     
     public Person(){} 
     
     public Person(String name, String sex, IDCard idcard, Set<Address> addressSet){ 
         this.sex = sex; 
         this.name = name; 
         this.idcard = idcard; 
         this.addressSet = addressSet; 
    } 

     public String getSex() { 
         return sex; 
    } 

     public  void setSex(String sex) { 
         this.sex = sex; 
    } 

     public String getName() { 
         return name; 
    } 

     public  void setName(String name) { 
         this.name = name; 
    } 

     public Set<Address> getAddressSet() { 
         return addressSet; 
    } 

     public  void setAddressSet(Set<Address> addressSet) { 
         this.addressSet = addressSet; 
    } 

     public IDCard getIdcard() { 
         return idcard; 
    } 

     public  void setIdcard(IDCard idcard) { 
         this.idcard = idcard; 
    } 

     public  static  double getVersion() { 
         return VERSION; 
    } 
} package fan.tutorial.model; 

public  class IDCard { 

     private  long number; 
     
     public IDCard(){} 
     
     public IDCard( long number){ 
         this.number = number; 
    } 

     public  long getNumber() { 
         return number; 
    } 

     public  void setNumber( long number) { 
         this.number = number; 
    } 
} package fan.tutorial.model; 

public  class Address { 

     private String name; 
     
     public Address(){} 
     
     public Address(String name){ 
         this.name = name; 
    } 

     public String getName() { 
         return name; 
    } 

     public  void setName(String name) { 
         this.name = name; 
    } 
} package fan.tutorial.action; 

import java.util.Map; 
import java.util.Set; 
import java.util.List; 
import java.util.HashSet; 
import java.util.ArrayList; 
import java.util.LinkedHashMap; 
import fan.tutorial.model.IDCard; 
import fan.tutorial.model.Person; 
import fan.tutorial.model.Address; 
import com.opensymphony.xwork2.Action; 
import org.apache.struts2.interceptor.RequestAware; 
import org.apache.struts2.interceptor.SessionAware; 
import org.apache.struts2.interceptor.ApplicationAware; 

public  class DataAction  implements Action, RequestAware, SessionAware, ApplicationAware { 
     
     private String author; 
     private String subject; 
     private Person person; 
     private List<Person> personList; 
     private Map<String, String> map; 
     private Map<String, Object> request; 
     private Map<String, Object> session; 
     private Map<String, Object> application; 
     private  int[] array = {8, 0, 9, 1, 3, 4, 2, 5, 7, 6}; 

     public String execute()  throws Exception { 
         
        subject = "fan-tutorial"; 
         
        Set<Address> addressSet =  new HashSet<Address>(2); 
        addressSet.add( new Address("廣東茂名")); 
        addressSet.add( new Address("廣東廣州")); 
        person =  new Person("fan", "male",  new IDCard(3115981L), addressSet); 
         
        personList =  new ArrayList<Person>(3); 
        addressSet =  new HashSet<Address>(1); 
        addressSet.add( new Address("雲南麗江")); 
        personList.add(person); 
        personList.add( new Person("chen", "female",  new IDCard(3575982L), addressSet)); 
        addressSet =  new HashSet<Address>(1); 
        addressSet.add( new Address("廣東潮汕")); 
        personList.add( new Person("chai", "female",  new IDCard(3115983L), addressSet)); 
         
        map =  new LinkedHashMap<String, String>(2); 
        map.put("username", "fan"); 
        map.put("password", "yun"); 
         
        request.put("message", "hey request"); 
        session.put("message", "hey session"); 
        application.put("message", "hey application"); 
         
         return SUCCESS; 
         
    } 

     public String getSubject() { 
         return subject; 
    } 

     public Person getPerson() { 
         return person; 
    } 

     public List<Person> getPersonList() { 
         return personList; 
    } 

     public  int[] getArray() { 
         return array; 
    } 

     public Map<String, String> getMap() { 
         return map; 
    } 

     public String getAuthor() { 
         return author; 
    } 

     public  void setAuthor(String author) { 
         this.author = author; 
    } 

     public  void setRequest(Map<String, Object> request) { 
         this.request = request; 
    } 

     public  void setSession(Map<String, Object> session) { 
         this.session = session; 
    } 

     public  void setApplication(Map<String, Object> application) { 
         this.application = application; 
    } 
} < struts > 

   < constant  name ="struts.ognl.allowStaticMethodAccess"  value ="true" /> 
   
   < package  name ="default"  extends ="struts-default" > 
     < default-action-ref  name ="defaultAction"  /> 
     < action  name ="defaultAction" > 
       < result  type ="redirect" >test?author=fan </ result > 
     </ action > 
     < action  name ="test"  class ="fan.tutorial.action.DataAction" > 
       < result >/index.jsp </ result > 
     </ action > 
   </ package > 

</ struts >

OGNL 訪問物件屬性

< s:property  value ="subject" /> 
< s:property  value ="person.name" /> 
< s:property  value ="person.idcard.number" />

OGNL 呼叫方法

< s:property  value ="person.getName()" /> 
< s:property  value ="person.name.toUpperCase()" />

OGNL 呼叫靜態屬性

< s:property  value ="@[email protected]" />

OGNL 呼叫靜態方法

<!--  在 struts.xml 中新增下面這行配置  --> 
<!--  <constant name="struts.ognl.allowStaticMethodAccess" value="true"/>  --> 
< s:property  value ="@[email protected]()" />

OGNL 呼叫構造方法

< s:property  value ="new fan.tutorial.model.Address('廣東茂名').name" />

OGNL 使用索引訪問陣列和列表

< s:property  value ="array[0]" /> 
< s:property  value ="personList[0].name" />

OGNL 操作符運算

< s:property  value ="array[0] + 1" /> 
< s:property  value ="array[0] - 1" /> 
< s:property  value ="array[0] * 2" /> 
< s:property  value ="array[0] / 2" /> 
< s:property  value ="array[0] % 3" />

OGNL 邏輯運算子

< s:set  name ="x"  value ="5" /> 
< s:property  value ="#x in array" /> 
< s:property  value ="#x not in array" /> 
< s:property  value ="#x > array[0]" /> 
< s:property  value ="#x >= array[0]" /> 
< s:property  value ="#x < array[0]" /> 
< s:property  value ="#x <= array[0]" /> 
< s:property  value ="#x == array[0]" /> 
< s:property  value ="#x != array[0]" />

OGNL 訪問命名物件 ( parameters、request、session、application、attr )

< s:property  value ="#parameters.author" /> 
< s:property  value ="#request.message" /> 
< s:property  value ="#session.message" /> 
< s:property  value ="#application.message" /> 
< s:property  value ="#attr.message" />

OGNL 訪問集合的偽屬性

型別 偽屬性 偽屬性對應的 Java 方法
List
Set
Map
size
isEmpty
List.size()        List.isEmpty()
Set.size()        Set.isEmpty()
Map.size()       Map.isEmpty()
List
Set
iterator List.iterator()
Set.iterator()
Map keys
values
Map.keySet()
Map.values()
Iterator next
hasNext
Iterator.next()
Iterator.hasNext()
< s:property  value ="personList.size" /> 
< s:property  value ="personList.isEmpty" /> 
< s:property  value ="map.keys" /> 
< s:property  value ="map.values" /> 
< s:property  value ="personList.iterator.hasNext" /> 
< s:property  value ="personList.iterator.next.name" /> 
< s:property  value ="person.addressSet.iterator.hasNext" /> 
< s:property  value ="person.addressSet.iterator.next.name" />

OGNL 迭代集合

型別 偽屬性 偽屬性的作用描述
IteratorStatus index 當前元素的索引
IteratorStatus first 當前元素是否是集合的第一個元素
IteratorStatus last 當前元素是否是集合的最後一個元素
IteratorStatus count 當前迭代元素的數量,count = index + 1
IteratorStatus even index + 1 是否為偶數
IteratorStatus odd index + 1 是否為奇數
< table > 
   < tr  align ="center" > 
     < td  width ="2%" >索引 </ td > 
     < td  width ="5%" >值 </ td > 
     < td  width ="8%" >當前迭代的數量 </ td > 
     < td  width ="8%" >迭代奇偶性 </ td > 
     < td  width ="8%" >集合第一個元素 </ td > 
     < td  width ="8%" >集合最後一個元素 </ td > 
   </ tr > 
   < s:iterator  value ="array"  var ="a"  status ="status" > 
     < tr  align ="center" > 
       < td > 
         < s:property  value ="#status.index" /> 
       </ td > 
       < td > 
         < s:property /> 
       </ td > 
       < td > 
         < s:property  value ="#status.count" /> 
       </ td > 
       < td > 
         < s:if  test ="#status.even" >偶 </ s:if > 
         < s:if  test ="#status.odd" >奇 </ s:if > 
       </ td > 
       < td > 
         < s:if  test ="#status.first" >是 </ s:if > 
         < s:else >否 </ s:else > 
       </ td > 
       < td > 
         < s:if  test ="#status.last" >是 </ s:if > 
         < s:else >否 </ s:else > 
       </ td > 
     </ tr > 
   </ s:iterator > 
</ table >

OGNL 投影

如果把集合中的資料想象成是資料庫表中的資料,那麼,投影就是從這張表中選取某一列所構成的一個新的集合。投影的語法:collection.{expression} < s:property  value ="personList.{name}" />

OGNL 過濾

OGNL 過濾也稱為選擇,就是把滿足 OGNL 表示式的結果選擇出來構成一個新的集合。
過濾的語法:collection.{?expression} 或 collection.{^expression} 或 collection.{$expression}
符號 作用
? 選取與邏輯表示式匹配的所有結果
^ 選取與邏輯表示式匹配的第一個結果
$ 選擇與邏輯表示式匹配的最後一個結果
#this 代表當前迭代的元素
< s:property  value ="array.{?#this > 5}" /> 
< s:property  value ="array.{^#this > 5}" /> 
< s:property  value ="array.{$#this > 5}" />

OGNL 投影和過濾

< s:property  value ="personList.{?#this.sex.equals('female')}.{name}" /> 
< s:property  value ="personList.{^#this.sex.equals('female')}.{name}" /> 
< s:property  value ="personList.{$#this.sex.equals('female')}.{name}" />

OGNL %{ } 語法

對於 ${ } 也許你並不會陌生,${ } 是 EL 表示式的語法,這裡的 %{ } 是 OGNL 表示式的語法。
也 許你開始困惑,上面示例不是都在使用 OGNL 表示式嗎?!沒見 %{ } 出現過啊!好眼力!凡是屬於 OGNL 表示式的串,你都可以使用 %{ } 來將它們包裹住,但這不是必須的。例如 <s:property value="expression" /> 中的 expression 在任何時候都是被當做 OGNL 表示式來處理的。 < s:property  value ="subject" />   <!--  subject被OGNL進行表示式求值輸出  --> 
< s:property  value ="i love java so much" />   <!--  什麼都不輸出  --> 第2行之所以什麼都不輸出,是因為執行時環境把 i love java so much 這個字串也當做是一個 OGNL 表示式來處理了,但在 OGNL 上下文中並找不到與這個 KEY 對應的值,因此什麼都沒有輸出。
這是由於 <s:property /> 標籤的 value 屬性是 Object 型別引起的,凡是 Object 型別的標籤屬性的值,都會被當做是一個 OGNL 表示式來處理。

相關推薦

Struts2中的OGNL(和標籤庫一起使用)

#符號的用途一般有三種。 —    訪問非根物件屬性,例如#session.msg表示式,由於Struts 2中值棧被視為根物件,所以訪問其他非根物件時,需要加#字首。實際上,#相當於ActionContext. getContext();#session.msg表示式相當於ActionContex

Struts2 配置

name con 默認 -name 動態 redirect man 執行過程 struts 1.Struts2登錄執行過程 頁面發送請求->核心控制器(StrutsPrepareAndEecuteFileter) ->Action->Result->

Struts2配置

method software ext.get 不存在 相同 patch ant name屬性 調用 1.Namespace 1)namespace決定action的訪問路徑,默認為“”,可以接受所有路徑的Action;

01-struts2配置

調試 dev efault nbsp config patch 錯誤 public include 1 struts.xml配置詳解 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts P

Struts2標籤 %{ } %{# }

?<%@ taglib prefix="s" uri="/struts-tags" %> 一.Struts2的值棧l結構? 1.root--結構是List集合 2.context--結果是map集合 可通過jsp頁面<s:debug></s:debug&

struts2 標籤

要使用Struts2的標籤,只需要在JSP頁面新增如下一行定義即可:<%@ taglib prefix="s" uri="/struts-tags"%> Struts2的標籤共分為五大類: 一、邏輯控制標籤 用於進行邏輯控制輸出,主要分為以下幾類: 1、條

Struts2 國際化

*.JSP中使用國際化資源 建立XXX_zh_CN.properties 配置檔案 XXX可以任意(放在src目錄下) #user=使用者名稱 #password=密碼 user=\u7528\u6237 password=\u5BC6\u7801 對應*.jsp檔案

spring和struts2整合

首先,我們要了解,web.xml中的各種元素在web容器中的載入順序:listener(監聽器)>filter(過濾器)>servlet. 在web.xml中配置如下: <?xml version="1.0" encoding="UTF-8"?>

Struts2配置_配置Action

 當訪問/News_delete時,name屬性中的第一個”*”匹配News,第二個”*”匹配delete,class屬性中使用的記號是{1},所以被News所替換,method屬性中使用的記號是{2},於是被delete所替換。結果對映中使用的記號是{0},於是被整個URL替換,即News_delete所替

Struts2_ValueStack,OGNL

一、ValueStack     1.ValueStack是一個介面,在struts2中使用OGNL(Object-Graph Navigation Language)表示式實際上是使用         實現了ValueStack介面的類OgnlValueStack.它是V

Struts2註解

使用註解來配置Action的最大好處就是可以實現零配置,但是事務都是有利有弊的,使用方便,維護起來就沒那麼方便了。  要使用註解方式,我們必須新增一個額外包:struts2-convention-plugin-2.x.x.jar。  雖說是零配置的,但struts.x

myeclipse使用maven構建struts2專案

零,maven的配置 首先去官網下載最新版maven,然後解壓,配置環境變數         然後開啟myeclipse,開啟window->preferences 不使用內嵌的maven,我們使用自己安裝的maven 然後配置settings.xml的路徑,然後更

Struts2入門

如何搭建Struts2專案 匯入相關架包 編寫web.xml,配置strus2過濾器 <filter> <filter-name>struts2</filter-name>

【基於初學者的SSH】struts2 值棧的struts2標簽庫+ognl表達式

radi ring etl action 值棧 多選 https submit 技術分享 一:什麽是值棧:struts2裏面本身提供的一種存儲機制,類似於域對象,值棧,可以存值和取值  特點:先進後出,最上面的元素叫做棧頂,也叫壓棧。  <s:debug><

Java程式設計師從笨鳥到菜鳥之(四十八)細談struts2(十)ognl概念和原理

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

struts2中s:iterator 標籤的使用OGNL用法

User物件屬性獲取 如User中有username和password欄位 獲取username屬性<s:property value="user.username" /> 獲取password屬性<s:property value="user.password" /> 若User中又

Struts2 OGNL使用

OGNL OGNL ( Object Graph Navigation Language ),物件圖導航語言。這是一種強大的表示式語言,通過它可以非常方便的來操作物件屬性。在 Struts2 中,OGNL 需要和 Struts2 標籤庫配套來使用。 OGNL conte

struts2基礎探索之OGNL表示式

OGNL概述: OGNL是一種可以吧UI元素(如table和input等基礎元素)和model object(模型物件)繫結的語言,且通過OGNL的TypeConverter機制可以更容易實現值型別的轉換 .在struts2中使用OGNL表示式實際上是使用實

細談struts2(十)ognl概念和原理

       在struts2中,根物件ValueStack的實現類為OgnlValueStack,該物件不是我們想像的只存放單個值,而是存放一組物件。在OgnlValueStack類裡有一個List型別的root變數,就是使用他存放一組物件 |--request |--application context

Struts2學習第三課 Struts2

request end apach -1 sso struts2 input div available 接著上次的課程 這次我們看struts.xml 修改如下:這裏是加上命名空間,默認的是不加,我們手動加上時就要在訪問時加上命名空間。 <?xml version