下拉菜单未填充,我的错误在哪里?

Drop down menu not populating, where is my error?

所以,我纠结了2天才明白我的错误是什么。我的下拉列表未填充数据库中的数据。我正在使用 Java EE 和 MySQL.

我可以毫无问题地将数据插入数据库,但是当我出于某种原因检索它时,jsp 没有正确执行它的操作,所以我总是让下拉列表为空。 这是我正在使用的table:

create table category(
    category_id int auto_increment,
    name varchar(30),
        primary key(category_id)
        );

这是我正在使用的servlet 和执行查询的方法。如您所见,我返回了一个对象列表,然后将其作为请求属性添加到 doGet 方法中。所以我想直到这里一切都应该正常工作。

public class DropDownServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        try {
            List<Category> categories = retrieveCategories();
            request.setAttribute("categories", categories);
            RequestDispatcher view = request.getRequestDispatcher("viewdropdown.jsp");
            view.forward(request, response);
        } catch (ClassNotFoundException | SQLException | IOException ex) {
            ex.printStackTrace();
        }
    }

    public static List<Category> retrieveCategories() throws ClassNotFoundException, SQLException {
        Connection conn = DatabaseConnection.initializeConnection();
        String query = "Select * from category";
        PreparedStatement pstmnt = conn.prepareStatement(query);
        List<Category> categories = new ArrayList<>();


        ResultSet rs = pstmnt.executeQuery();

        while (rs.next()) {

            int id = rs.getInt("category_id");
            String name = rs.getString("name");

            Category cat = new Category(id,name);
            categories.add(cat);

        }

        conn.close();
        return categories;
    }

这里是带有下拉列表的 jsp,它没有显示它应该显示的数据。

<html>

<head>
    <title>Dropdown page</title>
</head>

<body>
<h1>The names of the categories are the following:</h1>

<select id ="dropdown">
    <c:forEach items="${categories}" var="category">
        <option value = "${category.name}">${category.name}</option>
    </c:forEach>
</select>
    <br>
    <br>

</body>
</html>

编辑: 因此,我创建了这个硬编码测试方法来测试我的代码,并将其添加为请求参数,就像我将其他方法添加到数据库查询中一样。我的 DropDown 仍然是空的,所以问题可能出在我尝试在 jsp 中显示项目的方式。我认为它可能在我的循环中。

public static List<Category> testMethod(){
        List<Category> list = new ArrayList<>();
        Category one = new Category(1,"Blue");
        Category two = new Category(2,"Red");
        list.add(one);
        list.add(two);

        return list;

    }

看起来 ${categories} 是一个空集合。

首先,确保您已将 JSTL 核心库导入 JSP 页面。这是通过将

<%@ taglib prefix="c" uri = "http://java.sun.com/jsp/jstl/core" %>

在 JSP 页面的顶部。

此外,您可以在 JSP 端检查集合是否为空,方法是在某处添加:

<c:out value="${categories.size()}" />.

此外,您直接在 HTML <option> 标签之间使用表达式语言,因此您还需要添加:

<%@ page isELIgnored = "false" %>

在 JSP 页面的顶部,使其可评估为适当的值,而不是呈现纯文本。