在 Struts 開發中,下拉選單(<html:select>)常被用來實現單選功能。根據資料來源的不同,主要有三種構建選項的方式:直接在 JSP 中硬編碼、從 ActionForm 集合動態載入、以及從 Request 域獲取集合。掌握這三種方式,能靈活應對不同業務場景。
這是最直觀的方式,適用於選項固定、極少變動的場景(如城市列表、狀態碼)。直接在 JSP 頁面的 <html:select> 標籤內嵌套多個 <html:option> 標籤,指定 value 與顯示文字。
<html:select property="city">
<html:option value="010">北京市</html:option>
<html:option value="020">廣州市</html:option>
<html:option value="021">上海市</html:option>
</html:select>
優點: 簡單直觀,無需後端邏輯配合。
缺點: 維護成本高,修改選項需改動 JSP,不適合動態業務。
適合選項需由後端動態決定、且需在多個頁面複用的場景。將選項數據封裝在 ActionForm 的 List 屬性中,JSP 通過 property、label、value 屬性映射。
private List cityList = new ArrayList();
public List getCityList() { return cityList; }
reset() 方法中初始化數據(或從 Service/DAO 獲取):
cityList.add(new LabelValueBean("北京市", "010"));
cityList.add(new LabelValueBean("廣州市", "020"));
cityList.add(new LabelValueBean("上海市", "021"));
<html:select property="city2">
<html:optionsCollection property="cityList" label="label" value="value"/>
</html:select>
關鍵點: LabelValueBean 來自 org.apache.struts.util,封裝「標籤-值」對。此方式實現了數據與視圖分離,便於維護。
適合選項數據臨時、僅當前請求有效、或由攔截器/Filter 準備數據的場景。在 JSP 中使用 Scriptlet(或 JSTL/EL)將集合放入 Request,再由 <html:options> 的 collection 屬性引用。
<%
List cityList = new ArrayList();
cityList.add(new LabelValueBean("北京市", "010"));
cityList.add(new LabelValueBean("廣州市", "020"));
cityList.add(new LabelValueBean("上海市", "021"));
request.setAttribute("list", cityList); // 必須放入 request 域
%>
<html:select property="city3">
<html:options collection="list" labelProperty="label" property="value"/>
</html:select>
注意: 集合鍵名(list)需與 collection 屬性值一致。雖示例用 Scriptlet,實際項目建議用 Controller 準備數據、JSP 用 EL 表達式 ${list} 獲取,避免業務邏輯污染視圖。
| 方式 | 適用場景 | 維護性 | 靈活度 |
|---|---|---|---|
| <html:option> | 固定、少量、極少變動的選項 | 低 | 低 |
| <html:optionsCollection> | 動態數據、多頁複用、需分頁/緩存 | 高 | 高 |
| <html:options> | 請求級臨時數據、跨組件傳遞選項 | 中 | 中 |
現代開發中,推薦優先使用方式二,配合 Service 層查詢數據庫、緩存熱點數據,實現高性能、易維護的下拉選單。若項目已遷移至 Spring MVC,則可直接使用 <form:select> 搭配 <form:options> 或 <form:options items="${cityList}" itemValue="value" itemLabel="label"/>,體驗更佳。