[英]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>
是的,这是可能的,并且有几种方法可以实现:
使用脚本:(假设完成了所有必需的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>
使用c:forEach
或c:if
标记使用JSTL从列表中过滤掉所有不需要的元素
使用专门开发的自定义标签从列表中过滤掉除“加拿大”以外的所有国家
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.