我把它作为JSP页面,我想要一个组合框来填充数据库中表的值。 我有一个类Assembly和一个Class Assembly,在Assemblys中我将每个记录作为Assembly的一个实例并将其放在一个列表中。但我无法在JSTL中检索它?这是为什么?
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
.....
<select name = "assembly">
<c:forEach var ="item" items="${Assemblys}">
<option value="${item.id}">${item.Name}</option>
</c:forEach>
</select>
这是类Assembly
public class Assembly {
public String Name;
public int cost;
public int id;
public Assembly(String Name, int cost, int id) {
this.Name = Name;
this.cost = cost;
this.id = id;
}
}
这是班级大会
public class Assemblys {
List<Assembly> list = new ArrayList<Assembly>();
public Assemblys(){
list = getAssemblys();
}
private List<Assembly> getAssemblys() {
try {
Connection conn = MysqlConnect.conn();
PreparedStatement pstmt = null;
ResultSet rs = null;
String Query = "Select * from tbl_assembly";
pstmt = conn.prepareStatement(Query);
rs = pstmt.executeQuery();
while (rs.next()) {
Assembly ass = new Assembly(rs.getString(2),rs.getInt(3),rs.getInt(1));
list.add(ass);
}
conn.close();
} catch (SQLException ex) {
Logger.getLogger(Assemblys.class.getName()).log(Level.SEVERE, null, ex);
}
return list;
}
}
为什么我的下拉列表空白?我不明白。 我以为这是正确的代码?
非常感谢提前!
答案 0 :(得分:1)
首先,您应该将getter添加到Assembly类。
public class Assembly {
public String Name;
public int cost;
public int id;
public String getName() {
return this.Name;
}
public int getId() {
return this.id;
}
public Assembly(String Name, int cost, int id) {
this.Name = Name;
this.cost = cost;
this.id = id;
}
}
第二次将getList方法添加到Assemblys
public class Assemblys {
List<Assembly> list = new ArrayList<Assembly>();
public List<Assembly> getList() {
return this.list;
}
public Assemblys(){
list = getAssemblys();
}
private List<Assembly> getAssemblys() {
try {
Connection conn = MysqlConnect.conn();
PreparedStatement pstmt = null;
ResultSet rs = null;
String Query = "Select * from tbl_assembly";
pstmt = conn.prepareStatement(Query);
rs = pstmt.executeQuery();
while (rs.next()) {
Assembly ass = new Assembly(rs.getString(2),rs.getInt(3),rs.getInt(1));
list.add(ass);
}
conn.close();
} catch (SQLException ex) {
Logger.getLogger(Assemblys.class.getName()).log(Level.SEVERE, null, ex);
}
return list;
}
}
现在是jsp
<select name = "assembly">
<c:forEach var ="item" items="${Assemblys.list}">
<option value="${item.id}">${item.Name}</option>
</c:forEach>
</select>
答案 1 :(得分:1)
你需要一个servlet或在jsp中使用scriptlet(标记为坏练习)来调用类程序集。你指定的标签,我猜你正在使用servlet / jsp应用程序。
jsp中使用的程序集名称应该在请求对象中作为属性。您为Assemblys指定的密钥可用于获取列表。
答案 2 :(得分:0)
替换
<c:forEach var ="item" items="${Assemblys}">
与
<c:forEach var ="item" items="${Assemblys.list}">
编辑:
结合@ user2006574和@AntonIlinchik答案,你必须将getters添加到Assembly,将Assemblys中的getter更改为public access。
另外,发布调用Assemblys
构造函数的代码。