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

问题描述 投票:-1回答:1

所以,我已经花了2天的时间来了解我的错误。我的下拉列表没有填充数据库中的数据。我正在使用Java EE和Mysql。

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

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

Rhis是我正在使用的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>

编辑:所以我创建了这个硬编码的测试方法来测试我的代码,并将其作为请求参数添加到与使用DB查询添加其他方法相同的方式。我的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;

    }
java mysql jsp servlets dropdown
1个回答
0
投票

好像${categories}是一个空集合。

首先,请确保已将JSTL Core库导入到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页面的顶部,使其可以评估为适当的值,而不是呈现纯文本。

© www.soinside.com 2019 - 2024. All rights reserved.