需求:Session 中存有 List,每個 Question 包含動態選項 option1..n,JSP 頁面遍歷渲染單選題界面。
List list = ...;
session.setAttribute("listQuestionNaireQuestion", list);
Question 類建議設計:
public class Question {
private String questionText;
private List options; // 動態選項列表
// getter/setter
}
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="https://java.sun.com/jsp/jstl/functions" %>
<c:forEach items="${sessionScope.listQuestionNaireQuestion}" var="q" varStatus="status">
<div class="question-block">
<h3>${status.count}. ${q.questionText}</h3>
<c:forEach items="${q.options}" var="opt" varStatus="optStatus">
<div class="option-item">
<input type="radio" name="q_${status.index}" value="${optStatus.index}" id="opt_${status.index}_${optStatus.index}">
<label for="opt_${status.index}_${optStatus.index}">${opt}</label>
</div>
</c:forEach>
</div>
</c:forEach>
c:forEach 遍歷問題列表,varStatus 提供索引用於生成唯一 name (同組單選)。c:forEach 遍歷動態選項列表 q.options,無需固定 option1/2/3 字段。varStatus.index (從 0 開始) 用於生成唯一 id 和 value。option1、option2,可在後端轉換為 List 或 JSP 中用 fn:length 判斷非空字段輸出。**不使用** <% ... %>,改用 JSTL/EL,代碼清晰、易維護、符合 MVC 分層。
此結構完美支撐任意數量問題、任意數量選項的動態渲染。