我正在尝试使用jsp
和servlet
文件开发Web应用程序来学习Java JBDC。目前,我想返回Category
个对象的列表,其中Objects
代表ResultSet
中的一行。每行应包含cat_id
和cat_name
。
crm_categories
表在MySQL数据库中看起来像这样。
在index.jsp文件中,我实例化JDBC
并像这样调用getCategories()
方法:
dbCon conn = new dbCon();
List<Object> catList;
// get a list of all categories
catList = conn.getCategories();
以下是我简化的dbCon
课程:
@WebServlet(description = "Handles connection to MySql database", urlPatterns = { "/dbh" })
public class dbCon extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Connection conn;
private static final String driver = "com.mysql.jdbc.Driver", host = "jdbc:mysql://hostname/", dbName = "dbname", username = "name", password = "pow";
String sql;
ResultSet rs;
PreparedStatement prep;
Post post;
Category cat;
List<Object> catList;
/**
* @see HttpServlet#HttpServlet()
*/
public dbCon() {
try{
rs = null;
prep = null;
conn = getConnection();
} catch (Exception e){
e.printStackTrace();
}
}
public static Connection getConnection() throws Exception {
try{
Class.forName(driver);
Connection conn = (Connection) DriverManager.getConnection(host + dbName, username, password);
return conn;
} catch(Exception e){
e.printStackTrace();
}
return conn;
}
public List<Object> getCategories() throws Exception{
try{
this.catList = new ArrayList<Object>();
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"));
catList.add(cat);
}
} catch(Exception e){
e.printStackTrace();
}
return catList;
}
类别类:
@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;
}
}
有人可以告诉我为什么getCategories()
方法会为null
返回catList
值?
答案 0 :(得分:0)
getCategories()
方法是否会捕获异常?
如果是这种情况,则返回的catList
为null
,因为this.catList = new ArrayList<Object>();
已在try块中完成。在try块之前移动对象实例化应修复空指针问题。