我写了一个由数据库填充的下拉列表。这是我在JSP文件中的下拉代码。
<td>Category:</td>
<%
try {
dbConnect dbConnect = new dbConnect();
Connection currentCon = dbConnect.Connect();
System.out.println("Connection sucess");
String sql = "SELECT * FROM categories";
PreparedStatement ps = currentCon.prepareStatement(sql);
ResultSet rs = ps.executeQuery();%>
<td><select name="category" class="form-control" required>
<%
while (rs.next()) {
String cname = rs.getString("category_name");
String id = rs.getString("category_id");
System.out.println(id);
%>
<option value="<%= id%>"><%= cname%></option>
<%
}
%>
</select>
<%
} catch (SQLException sqe) {
out.println(sqe);
}
%>
</td>
相关的servlet代码是;
String id = request.getParameter("category");
在JSP的下拉列表中,它打印类别中的所有ID。但是,当涉及到servlet时,它将返回null。如何解决此问题?
答案 0 :(得分:1)
在您的代码中我没有找到任何<form> tag
或submit
按钮,请尝试以下代码:
<td>Category:</td>
<form method="post" action="yourservleturl">//form tag for submitting data
<%
try {
dbConnect dbConnect = new dbConnect();
Connection currentCon = dbConnect.Connect();
System.out.println("Connection sucess");
String sql = "SELECT * FROM categories";
PreparedStatement ps = currentCon.prepareStatement(sql);
ResultSet rs = ps.executeQuery();%>
<td><select name="category" class="form-control" required>
<%
while (rs.next()) {
%>
<option value="<%=rs.getString("category_id")%>"><%=rs.getString("category_name")%></option> // printing option values
<%
}
%>
</select>
<%
} catch (SQLException sqe) {
out.println(sqe);
}
%>
<input type="submit" value="submit">///submit btn
</form>
</td>
还可以通过String id = request.getParameter("category");
获取下拉值。应该可以使用。
答案 1 :(得分:0)
应该在while循环外发出局部变量,因为在while循环后需要该值。
<%
try {
dbConnect dbConnect = new dbConnect();
Connection currentCon = dbConnect.Connect();
System.out.println("Connection sucess");
String sql = "SELECT * FROM categories";
PreparedStatement ps = currentCon.prepareStatement(sql);
ResultSet rs = ps.executeQuery();%>
String cname = null;
String id = null;
<td><select name="category" class="form-control" required>
<%
while (rs.next()) {
cname = rs.getString("category_name");
id = rs.getString("category_id");
System.out.println(id);
%>
此外,我建议您使用表达式语言而不是<%= id%>
更改
<option value="<%= id%>"><%= cname%></option>
<option value="${id}">${name}</option>
别忘了提交按钮。