【发布时间】:2014-07-25 00:27:54
【问题描述】:
我正在使用 jsp 创建一个网站。我有一个方法可以将JDBC 查询中的每一行作为对象返回。每个对象都被添加到一个列表中并返回到 jsp 文件中。
这是返回存储在 MySQL 数据库中的类别列表的方法:
public List<Object> getCategories() throws Exception{
this.catList = new ArrayList<Object>();
try{
sql = "SELECT cat_id, cat_name FROM crm_categories";
prep = conn.prepareStatement(sql);
rs = prep.executeQuery();
while(rs.next()){
cat = new Category();
cat.setAttributes(rs.getInt("cat_id"), rs.getString("cat_name"));
this.catList.add(cat);
}
} catch(Exception e){
e.printStackTrace();
}
return catList;
}
Category 对象如下所示:
@WebServlet("/Category")
public class Category extends HttpServlet {
private static final long serialVersionUID = 1L;
private String name;
private int id;
public Category() {
name = null;
id = 0;
}
public void setAttributes(int id, String name){
this.name = name;
this.id = id;
}
public String[] getAttributes(){
String[] attributes = {this.name, String.valueOf(this.id)};
return attributes;
}
}
我试图遍历对象列表。它将“测试”打印到浏览器 7 次,这是正确的类别数:
dbCon conn = new dbCon();
List<Object> catList;
// get a list of all categories
catList = conn.getCategories();
for (Object o : catList){
out.println("test");
}
如何访问每个类别getAttributes 方法?
【问题讨论】:
标签: java mysql jsp loops object