我知道以前曾经问过这个问题,但这对我不起作用。
我正在尝试使用jstl从数据库填充下拉列表,这是我用作usebean的类:
public class feedData {
Connection con;
public feedData() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "******";
con = DriverManager.getConnection(url, "**", "**");
}
public ArrayList<String> getUnis() throws SQLException {
ArrayList<String> uniList = new ArrayList<String>();
String tryquery = "select aff from libra.smalluniqdbtmp";
Statement stmt2 = con.createStatement();
ResultSet rs1 = stmt2.executeQuery(tryquery);
while (rs1.next()) {
uniList.add(rs1.getString("aff"));
}
return uniList;
}
public ArrayList<String> getRI() throws SQLException {
ArrayList<String> RIList = new ArrayList<String>();
String tryquery = "select interest from libra.riuniqdb";
Statement stmt2 = con.createStatement();
ResultSet rs1 = stmt2.executeQuery(tryquery);
while (rs1.next()) {
RIList.add(rs1.getString("aff"));
}
return RIList;
}
}
这是我的jsp:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<jsp:useBean id="obj" scope="page" class="uiLibraWeb2Pkg.feedData" />
<h1>Hello World!</h1>
<table border="1">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td> <form action="response.jsp">
<strong>Select a university:</strong>
<select name="affiliation">
<c:forEach var="aff" items="${obj.unis}">
<option value="${aff}"></option>
</c:forEach>
</select>
</form>
</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</body>
</html>
服务器日志和项目的构建输出中没有错误消息,但下拉列表为空。一直在努力,我不知道什么是错的。我还试图设置一个数据源并使用jstl迭代查询的结果集来完成它,但行为方式相同。
现在我不依赖任何数据源,但结果仍然相同。
帮助表示感谢, 感谢
答案 0 :(得分:5)
我还没有测试过你的代码,但是请在服务器端添加一个断点来检查列表中有多少元素。也许它在服务器端也是空的。
第二点是这段代码
<option value="${aff}"></option>
不向用户显示任何内容,因为它在HTML中呈现为没有文本的选项。也许它应该是
<option value="${aff}">${aff}</option>
答案 1 :(得分:1)
右键单击webbrowser中的HTML页面和查看源。很有可能你看到JSTL标签在那里被解开了。没错,你没有按照JSTL core taglib documentation在JSP的顶部导入JSTL taglib:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
(并且还不要忘记设置@Guido提到的选项标签)
如果这不能解决问题并且您得到无法识别的taglib的编译错误,那么这意味着有问题的servletcontainer没有附带JSTL,并且您必须自己安装JSTL。它基本上很简单:只需将jstl-1.2.jar放入您的网络应用的/WEB-INF/lib
并重新部署即可。
如果你想知道为什么JSP标签不需要它,那是因为它们默认已被JspServlet
识别。任何其他标记库应该在JSP之前显式声明为@taglib
。
与实际问题无关:您的JDBC代码看起来不正确。您没有关闭连接,从而泄漏资源。如果长时间反复运行,那么数据库将耗尽连接,您的应用程序将中断。您可能会发现this article对于学习如何正确使用JDBC代码非常有用。