我正在使用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;
}
}
我试图遍历对象列表。它将“test”打印到浏览器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
方法?
答案 0 :(得分:4)
问题是,getCategories
方法会返回List<Object>
,当它更有意义返回List<Category>
时:
public List<Object> getCategories() throws Exception{
// Note: this is now a *local* variable. There was no need for it to be an
// instance variable as far as I can see.
// If you're using Java 7 or higher, you can use new ArrayList<>(); too.
List<Category> catList = new ArrayList<Category>();
...
}
然后:
for (Category category : conn.getCategories()) {
out.println(Arrays.toString(category.getAttributes()));
}
答案 1 :(得分:1)
如果要访问Category
类型的方法,则必须有另一个声明:
dbCon conn = new dbCon();
List<Category> catList = conn.getCategories();
for (Category cat : catList) {
// here you can access "cat.getAttributes()"
}
当然,这需要您更改方法dbCon.getCategories()
:
public List<Category> getCategories() throws Exception{
this.catList = new ArrayList<Category>();
...
return catList;
}
由于catList
显然是一个字段,因此也必须更改。
答案 2 :(得分:1)
public List<Category> getCategories() throws Exception{
List<Category> tmp= new ArrayList<Category>();
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"));
tmp.add(cat);
}
} catch(Exception e){
e.printStackTrace();
}
this.catList = tmp;
return tmp;
}
已经发布了正确的答案,但是想知道这个方法中的you should not use class field
。如果您将同时在两个线程中启动此方法,则会导致某些数据库条目加倍(在某些情况下,所有条目都将加倍)。
使用本地字段,如果此方法应修改类字段,请在返回结果之前执行此操作。
访问对象当然是
for (Category c: getCategories()) {
c.getAttributes();
}