方法返回对象列表的NULL值

时间:2014-06-03 12:29:00

标签: java mysql jsp jdbc null

我正在尝试使用jspservlet文件开发Web应用程序来学习Java JBDC。目前,我想返回Category个对象的列表,其中Objects代表ResultSet中的一行。每行应包含cat_idcat_name

crm_categories表在MySQL数据库中看起来像这样。

Example of crm_categories table

在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值?

1 个答案:

答案 0 :(得分:0)

getCategories()方法是否会捕获异常?

如果是这种情况,则返回的catListnull,因为this.catList = new ArrayList<Object>();已在try块中完成。在try块之前移动对象实例化应修复空指针问题。