以表格格式显示来自js的servlet中的arraylist值

时间:2019-08-25 08:31:30

标签: java jsp arraylist iteration

从数据库中获取数据后,我试图在jsp表中显示学生数据

学生Servlet

ArrayList student = new ArrayList();
String selectSQL = "SELECT studentname from student";

while (rs.next()) {
    studentname = rs.getString(1);
    student.add(studentname);
}

request.setAttribute("student", student);
request.getRequestDispatcher("home.jsp").include(request, response);

home.jsp

<%
    ArrayList List = new ArrayList();
    String student = (String) request.getAttribute("student");
    List.add(student);

    Iterator<String> itr = List.iterator();
    while (itr.hasNext()) {
%>

<table>
    <tr>
        <th>Students</th>
    </tr>
    <tr>
        <td><%=itr%>
        </td>
    </tr>
</table>

<%
    }
%>

home.jsp部分出现错误。非常感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

在您的servlet中,

ArrayList student = new ArrayList();

应该是

List<String> student = new ArrayList<>();

不要使用原始类型。然后,在您的jsp中

List<String> al = (ArrayList<String>) request.getAttribute("student");
Iterator<String> itr = al.iterator();
while(itr.hasNext()){

<%=itr%>

应该是

<%= itr.next() %>