I am creating a website using jsp. I have a method that returns each row from a JDBC
query as an object. Each object is added to a list and returned to the jsp file.
This is the method that returns the list of categories stored in a MySQL database:
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;
}
The Category
object looks like this:
@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;
}
}
I have attempted to iterate through the list of objects. It prints "test" to the browser 7 times which is the correct number of categories:
dbCon conn = new dbCon();
List<Object> catList;
// get a list of all categories
catList = conn.getCategories();
for (Object o : catList){
out.println("test");
}
How do I access each Categories getAttributes
method?
The problem is that your getCategories
method returns a List<Object>
, when it would make more sense for it to return 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>();
...
}
Then:
for (Category category : conn.getCategories()) {
out.println(Arrays.toString(category.getAttributes()));
}
See more on this question at Stackoverflow