简体   繁体   English

ForEach循环遍历从外部类获取的ArrayList

[英]ForEach loop to iterate through ArrayList got from external Class

I've got two classes: Subject and Subjects . 我有两节课: SubjectSubjects Subject stores data containing data found in a database (id, name and abbreviation). Subject存储的数据包含在数据库中找到的数据(ID,名称和缩写)。 Subjects makes a database connection and returns an ArrayList containing Subject s. Subjects建立数据库连接并返回一个包含Subject的ArrayList。

Subject.java: Subject.java:

public class Subject {

   public int id;
   public String subjectName;
   public String subjectAbbr;

 //and some getters and setters

}

Subjects.java: 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;

    }

}

I've got signup.jsp , containing a dropdown select menu and I want the user be able to choose from the abbrevations found in the database. 我有signup.jsp ,其中包含一个下拉选择菜单,我希望用户能够从数据库中的缩写中进行选择。 So I can call Subjects.getAllFromSubject() and I get an ArrayList containing a number of Subject s. 所以我可以调用Subjects.getAllFromSubject() ,得到一个包含多个Subject的ArrayList。 I'd like to display all those Subject s abbrevations in a <select> -menu. 我想在<select>菜单中显示所有Subject的缩写。 This can be done by a forEach loop, but I'm am not sure how to do that and how to get the abbrevation from a Subject . 这可以通过forEach循环来完成,但是我不确定如何做到这一点以及如何从Subject获得缩写。

Any help would be greatly appreciated! 任何帮助将不胜感激!

I hope this help: 希望对您有所帮助:

index.jsp 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM