首先,您没有在 JSP 中使用任何 JSTL 标记。您正在使用 Struts 标签。您确实应该更喜欢 JSTL 标记。
现在,您的问题是设计问题。您应该有一个Question
实例列表,而不是 6 个字符串列表,其中Question
类将具有以下属性:
.
public class Question {
private String label;
private String option1;
// ...
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
// ...
}
现在,不必同时迭代 6 个列表,您只需迭代问题列表即可:
<logic:iterate name="questions" id="question">
<tr>
<td><bean:write name="question" property="label"/></td>
<td><bean:write name="question" property="option1"/></td>
...
</tr>
</logic:iterate>
或者,使用 JSTL 标签:
<c:forEach var="question" items="${questions}">
<tr>
<td><c:out value="${question.label}" /></td>
<td><c:out value="${question.option1}"/></td>
...
</tr>
</c:forEach>
Java 是一种面向对象的语言。使用对象。
此外,请考虑远离 Struts1,它是一个过时的、废弃的框架。
编辑:
好的。所以你首先需要一个Question
类。该类应命名为Question
,而不是Questions
,因为此类的每个实例都代表一个问题,而不是多个问题:
public class Question {
private String label;
private String option1;
// other fields omitted for brevity
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
// other getters and setters omitted for brevity
}
现在,当从表中读取行时,您应该Question
每行创建一个对象,并填写问题列表。由于列表包含几个问题,我们将命名它questions
而不是question
:
// this is an list of questions. It's empty initially
// this list isn't meant to contain Strings, and it can't.
// It will contain one Question object for each row in the table.
List<Question> questions = new ArrayList<Question>();
try{
Statement st = DBConnection.DBConnection.DBConnect();
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
// this block is executed for each row in the table.
// Each row is transformed into a Question object
Question question = new Question();
question.setLabel((rs.getString("ques_name"));
question.setOption1(rs.getString(3));
question.setOption2(rs.getString(4));
question.setOption3(rs.getString(5));
question.setOption4(rs.getString(6));
question.setAnswer(rs.getString(7));
// now that we have created a Question object and populated it with the
// cells of the row, we will add it to the list of questions:
questions.add(question);
}
// So now, we have a list of questions. Each element of the list is an object
// of type Question, which has a property label, a property option1, etc.
request.setAttribute("questions", questions);
}
现在在 JSP 中,我们可以遍历这个问题列表。在循环内,当前问题将被命名为“问题”。
<logic:iterate name="questions" id="question">
<tr>
<%-- let's write the property label of the current question
This will in fact call question.getLabel() and write it to the response
--%>
<td><bean:write name="question" property="label"/></td>
<%-- let's write the property option1 of the current question
This will in fact call question.getOption1() and write it to the response
--%>
<td><bean:write name="question" property="option1"/></td>
</tr>
</logic:iterate>