Struts 中 html options 的使用

2021-04-12 21:53:39 字數 2646 閱讀 8695

html:options是struts中比較複雜的乙個tage lib,用法靈活,但是sturts提供的原始碼exercise taglib中沒有提出常用jsp+actionform這樣形式的最直接的總結,現從中總結如下,分兩種情況:陣列和collection。

需求,要達到:

label 0

label 1

label 2

label 3

label 4

label 5

label 6

label 7

label 8

label 9

要實現上述效果,需要兩步:

第一:設定actionform,

也分兩小步:第一小步必須在actionform中,有一句

private collection beancollection;

public collection getbeancollection();

collection beancollection要確保是乙個實現,如arraylist,如果不是則會報no collection found的錯誤,struts的最大不方便就是一旦出問題,定位很難,不知道什麼地方使用錯誤,或忘記設定什麼了。

因為前面需求中option的value值和label值不一樣,那麼在beancollection中儲存的就是乙個value和label組成的物件,名為labelvaluebean,在labelvaluebean中有兩個屬性value和label,

在程式某個地方要為beancollection賦值,如:

vector entries = new vector(10); 

entries.add(new labelvaluebean("label 0", "value 0"));     

entries.add(new labelvaluebean("label 1", "value 1"));     

entries.add(new labelvaluebean("label 2", "value 2"));     

entries.add(new labelvaluebean("label 3", "value 3"));     

entries.add(new labelvaluebean("label 4", "value 4"));      

entries.add(new labelvaluebean("label 5", "value 5"));     

entries.add(new labelvaluebean("label 6", "value 6"));      

entries.add(new labelvaluebean("label 7", "value 7"));      

entries.add(new labelvaluebean("label 8", "value 8"));      

entries.add(new labelvaluebean("label 9", "value 9"));

然後執行setbeancollection(entries);

這樣actionform中的beancollection算有值了。

第二小步,需要設定selected,selected有兩種,單選和多選:

在actionform中必須有:

private string singleselect = "single 5"; 

public string getsingleselect()

public void setsingleselect(string singleselect)

或多選,多選必須是陣列:

private string beancollectionselect = ; 

public string getbeancollectionselect()

public void setbeancollectionselect(string beancollectionselect)

第二:在jsp中寫入tang lib語句如下:

其中testbean是actionform的名稱。

以上是html:options的collection解決方案,如果option值很少,簡單地可以實現為陣列,兩步:

第一:在actionform中,

private string values =

;  private string labels =

;private string selected = "magazine";  

public string getselected()

public void setselected(string selected)

public string getvalues()

public void setvalues(string values)

public string getlabels()

public void setlabels(string labels)

第二步在jsp中:

struts標籤庫的使用還是需要小心,不必完全使用struts的標籤庫,個人感覺struts這種替代html語句的標籤庫有一種牽強附會,給使用者掌握帶來難度,使用者除熟悉html外,還必須理解struts的對應標籤庫用法,而且這種除錯出錯,問題也無法準確定位,總是抽象地告訴你,no bean 或no form  

Struts中的用法

訪問map中所有的key 訪問map中所有的values 訪問map的大小 投影取到list中滿足條件的開頭的乙個元素的密碼 取到list中滿足條件的最後的乙個元素的密碼 從棧頂開始取一直取到指定的位置0表示棧底 value attrname value obj.attrname value obj...

Struts 心得 持續更新中

messageresources 的使用 在action類中定義了getresources httpservletrequest request 方法,該方法返回當前預設的messageresources 物件,它封裝了resource bundle中的文字內容。接下來action類就可以通過mes...

Struts中html options的使用

html options是struts中比較複雜的乙個tage lib,用法靈活,但是sturts提供的原始碼exercise taglib中沒有提出常用jsp actionform這樣形式的最直接的總結,現從中總結如下,分兩種情況 陣列和collection。需求,要達到 beancollecti...