我有两个课程:Subject
和Subjects
。 Subject
存储包含在数据库中找到的数据的数据(id,名称和缩写)。 Subjects
建立数据库连接并返回包含Subject
s。
Subject.java:
public class Subject {
public int id;
public String subjectName;
public String subjectAbbr;
//and some getters and setters
}
Subjects.java:
public class Subjects {
public ArrayList getAllFromSubject() throws SQLException {
Database DB = new Database();
String query = "SELECT * FROM `subject`;";
//DB.exequteQuery returns a ResultSet with the data from the query.
ResultSet result = DB.executeQuery(query);
ArrayList<Subject> output = new ArrayList();
while (result.next()) {
Subject subject = new Subject();
subject.setId(result.getInt("id"));
subject.setSubjectName(result.getString("subjectname"));
subject.setSubjectAbbr(result.getString("subjectabbr"));
output.add(subject);
}
DB.closeExistingConnection();
return output;
}
}
我有signup.jsp
,包含下拉选择菜单,我希望用户能够从数据库中找到的缩写中进行选择。所以我可以调用Subjects.getAllFromSubject()
并获得一个包含多个Subject
s的ArrayList。我想在Subject
- 菜单中显示所有这些<select>
缩写。这可以通过forEach循环完成,但我不知道如何做到这一点以及如何从Subject
获取缩写。
非常感谢任何帮助!
答案 0 :(得分:1)
我希望这有帮助:
的index.jsp
<%@page language="java" contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="jvanamerongen.example.Subjects"%>
<%@page import="jvanamerongen.example.Subject"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<% Subjects list = new Subjects(); %>
<select>
<% for(Subject s : list.getAllFromSubject()) { %>
<option value="<% out.print(s.getId()); %>"><% out.print(s.getSubjectAbbr()); %></option>
<%}%>
</select>
</body>
</html>