我已经参与了一段时间,尝试了不同的例子(包括我在这里找到的一些例子),并试图让它们适应我的需要。
我正在尝试在servlet中使用数据库查询来填充生成的结果html表单中的组合框。当它全部编译并且页面弹出一个组合框时,框中没有任何内容可供选择,这告诉我传递变量的方式有问题。
我基本上将我的方法缩小到两个,但两者都得到了相同的结果 有人可以看看并给我一个线索吗?
out.print(`"<tr><td>SoldWhich Home ID: `</td><td>"`);
//Query table for results to go into option box
ResultSet rs1 = null;
Statement stmt1 = null;
Connection con1 = null;
try {
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
ArrayList<String> soldWhich = new ArrayList<String>();
List<String> soldWhich = new ArrayList<String>();
while (rs1.next()){
for (int i=1;i<=rs1.getRow(); i++ ){
String value = rs1.getString(1);
soldWhich.add(value);
}
}
}
catch(Exception e){}
//Begin option box
out.print(`"<select width=\"150px\" align=\"right\" name=\"soldWhichBox\">"`);
String soldWhich[] = (String[])req.getAttribute("home_id");
//populate with query output
try{
for(String sh : soldWhich){
out.print(`"<option width=\"150px\" align=\"right\" value=\""+sh+"\">"+sh+"</option>"`);
}
rs1.close();
con1.close();
}
catch (Exception e){}
out.print(`"</select>"`);
out.print(`"</td></tr>"`);
另一种方法:
out.print(`"<tr><td>SoldWhich Home ID: </td><td>"`);
//Query table for results to go into option box
ResultSet rs1 = null;
Statement stmt1 = null;
Connection con1 = null;
try{
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home ORDER BY home_id";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
List<String> soldWhich = new ArrayList<String>();
while (rs1.next()){
soldWhich.add(rs1.getString(1));
}
}
catch(Exception e){}
//Begin option box
out.print(`"<select width=\"150px\" align=\"right\" name=\"soldWhichBox\">"`);
String soldWhich[] = (String [])req.getAttribute("home_id");
//populate with query output
try{
for(String sh : soldWhich){
out.print(`"<option width=\"150px\" align=\"right\" value=\""+sh+"\">"+sh+"</option>"`);
}
rs1.close();
con1.close();
}
catch (Exception e){}
out.print(`"</select>"`);
out.print(`"</td></tr>"`);
答案 0 :(得分:0)
我认为你实际上并没有在“for(String sh:soldWhich)”循环中获得值(sh)。你能尝试在简单的表格中打印这些值,看看你是否真的得到了数据吗?另外,为什么你不使用jstl来执行此任务?并且你的catch块不会记录任何错误,以防你实际上遇到一些不被注意的错误。
答案 1 :(得分:0)
您在哪里设置“home_id”请求属性,为什么要设置它?我认为您应该删除以下代码行,看看它是否有效。将代码修改为此。
List<String> soldWhich = null;
try {
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
soldWhich = new ArrayList<String>();
while (rs1.next()){
for (int i=1;i<=rs1.getRow(); i++ ){
String value = rs1.getString(1);
soldWhich.add(value);
}
}
}