簡體   English   中英

如何在Struts中過濾列表

[英]How can I filter a list in struts

我正在創建並傳遞給我的jsp的數組列表是

ArrayList countryList = new ArrayList();
countryList.add(new CountryData("1", "USA"));
countryList.add(new CountryData("2", "Canada"));
countryList.add(new CountryData("3", "Mexico"));
countryList.add(new CountryData("4", "Canada"));

在我正在使用的jsp頁面上顯示

<html:select property="country" >
<html:option value="0">Select Country</html:option>
<html:optionsCollection name="InputForm" property="countryList"
label="countryName" value="countryId" />
</html:select>

是否可以過濾jsp上的列表以僅在下拉列表中顯示加拿大

最簡單的操作可能是將CountryData的列表序列化為JSON(使用大量免費的Java JSON庫之一),並使用JavaScript過濾國家/地區數組。

在Java中:

String countryListAsJSON = serialize(countryList);
request.setAttribute("countries", countryListAsJSON);

在JSP中:

<script>
    var countries = ${countries};
    //...
</script>

將其轉換為以下HTML代碼:

<script>
    var countries = [{"countryId": "1", "countryName": "USA"}, {"countryId": "2", "countryName": "Canada"}, ...];
    //...
</script>

是的,這是可能的,並且有幾種方法可以實現:

  1. 使用腳本:(假設完成了所有必需的include指令)

     <%= List<CountryData> newList = new ArrayList<CountryData>(); %> <html:select property="country" > <html:option value="0">Select Country</html:option> <% for(CountryData cd:countryList) { if("Canada".equals(cd.getCountry())) { newList.add(cd); } } %> <html:optionsCollection name="InputForm" property="newList" label="countryName" value="countryId" /> </html:select> 
  2. 使用c:forEachc:if標記使用JSTL從列表中過濾掉所有不需要的元素

  3. 使用專門開發的自定義標簽從列表中過濾掉除“加拿大”以外的所有國家

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM