JSP 頁面常需根據後端資料動態生成表單控制項 (下拉選單、核取方塊、單選鈕),並自動勾選指定值。手寫 JSTL `
| 層級 | 檔案/類別 | 職責 |
|---|---|---|
| TLD 定義 | `/WEB-INF/tld/form.tld` | 宣告標籤名稱、屬性、Tag Handler 類別 |
| Tag Handler | `com.example.tag.FormTagSupport` (extends TagSupport) | 核心邏輯:讀取屬性、查詢資料、輸出 HTML |
| 資料模型 | `Option` (value, label, selected) | 統一選項資料結構 |
| Servlet/Controller | 準備 `List | 提供資料來源 |
| JSP 使用 | ` | 宣告式使用 |
public class SelectTag extends TagSupport {
private String name; // HTML name 屬性
private List
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="https://java.sun.com/xml/ns/javaee" version="2.1">
<tlib-version>1.0</tlib-version>
<short-name>form</short-name>
<uri>https://example.com/tags/form</uri>
<tag>
<name>select</name>
<tag-class>com.example.tag.SelectTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>items</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>value</name>
<required>false</required>
</attribute>
<attribute>
<name>cssClass</name>
<required>false</required>
</attribute>
</tag>
<!-- checkbox, radio 同理定義 -->
</taglib>
<%@ taglib prefix="form" uri="https://example.com/tags/form" %>
<!-- 單選下拉選單 -->
<form:select name="roleId" items="${roleList}" value="${user.roleId}" cssClass="form-control" />
<!-- 核取方塊群組 -->
<form:checkboxes name="permissionIds" items="${permList}" values="${user.permissionIds}" cssClass="checkbox-inline" />
<!-- 單選鈕群組 -->
<form:radios name="gender" items="${genderList}" value="${user.gender}" />
<select name="roleId" class="form-control">
<option value="1">管理員</option>
<option value="2" selected>編輯</option>
<option value="3">檢視者</option>
</select>
<span class="checkbox-inline">
<input type="checkbox" name="permissionIds" value="10"> 讀取</span>
<span class="checkbox-inline">
<input type="checkbox" name="permissionIds" value="11" checked> 寫入</span>
</span>
<label><input type="radio" name="gender" value="M" checked> 男</label>
<label><input type="radio" name="gender" value="F"> 女</label>