Я новичок в struts и недавно слышал, что использование jstl-тегов является наиболее предпочтительным способом, но мне сложно проходить время.
Questions.java
public class Questions {
private String label;
private String option1;
....
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
...
}
Это мой класс действий
PaperEdit val = (PaperEdit)form;
String sql = "SELECT * FROM "+val.getCategory();
List<Questions> question = new ArrayList<Questions>();
try{
Statement st = DBConnection.DBConnection.DBConnect();
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
question.add(rs.getString("ques_name"));
question.add(rs.getString(3));
question.add(rs.getString(4));
question.add(rs.getString(5));
question.add(rs.getString(6));
question.add(rs.getString(7));
}
request.setAttribute("ques", question);
}
Теперь Netbeans отображает все утверждения в цикле while с ошибками:
нет подходящего метода для метода add (String) List.add(int, Questions) не применим (фактические и формальные списки аргументов различаются по длине) метод List.add (вопросы) не применим (фактический аргумент String не может быть преобразован в Вопросы путем преобразования вызова метода)
Я пытаюсь получить эти данные на моей странице jsp, используя теги jstl. Это страница, на которой
display.jsp
<table width="60%" align="center" border="1px">
<logic:iterate name="ques" id="question">
<tr>
<td><bean:write name="question" property="ques_name"/></td>
</tr>
</logic:iterate>
</table>
Прежде всего, вы не используете какой-либо JSTL-тэг в своем JSP. Вы используете теги Struts. Вы действительно должны использовать теги JSTL.
Теперь ваша проблема - проблема дизайна. Вместо того, чтобы иметь 6 списков String, у вас должен быть один список экземпляров Question
, где класс 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 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 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 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>