展示一個完整的Struts 1.x自定義標簽DbSelectByDbWhere,從數據庫查詢城區數據並渲染<select>下拉框,支持指定表名、字段、條件、默認提示項與選中值。
繼承TagSupport,屬性對應TLD定義:table_name、id_col_name、select_id、name、name_col_name、condition、pleaseselect、sql_where。doStartTag()中:
ConnectionFactory)。select * from table where 1=1 and city_id=sql_where。ResultSet輸出<option>,匹配select_id添加selected屬性。finally關閉資源(DBclose工具類)。public int doStartTag() throws JspException {
// ... 參數預處理 ...
con = ConnectionFactory.getConnection();
if ("1".equals(pleaseselect)) pageContext.getOut().write("選擇城區");
String sql = "select * from " + table_name + " where 1=1 ";
if (!"".equals(sql_where)) sql += " and city_id=" + sql_where;
ps = con.prepareStatement(sql);
for (rs = ps.executeQuery(); rs.next(); ) {
String selected = rs.getString(name_col_name).equals(select_id) ? "selected" : "";
pageContext.getOut().write("<option value='" + rs.getString(id_col_name) + "' " + selected + ">" + rs.getString(name_col_name) + "</option>");
}
DBclose.close(rs, ps, con);
return SKIP_BODY;
}
.tld註冊標簽名selectResnodes、屬性與標簽類全限定名。<%@ taglib uri="/WEB-INF/xxx.tld" prefix="slotnode" %>。<slotnode:selectResnodes table_name="district" name_col_name="name" id_col_name="id" sql_where="${cityId}" select_id="${selectedDistrict}" pleaseselect="1" />。Connection/PreparedStatement/ResultSet字段,非線程安全,併發環境下應改為局部變量。<sql:query>+EL表達式。