代码如下:
DAOBase类:
package DAO;import java.sql.Connection;
import java.sql.SQLException;import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.sql.DataSource;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionContext;import exception.DaoException;public class DAOBase {
public DataSource datasource;

public Connection getConnection() throws DaoException{
ServletContext servletContext = ServletActionContext.getServletContext();
datasource = (DataSource) servletContext.getAttribute("dataSource");
Connection connection = null;
if(datasource != null){
try {
connection = datasource.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return connection;

}}DepartmentDAO 类,继承自:DAOBase
package DAO;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;import javax.sql.DataSource;import exception.DaoException;public class DepartmentDAO extends DAOBase {

public static String SEARCH_ALL_DEPARTMENT = "SELECT * FROM departmentinfo";

public  HashMap<Integer,String> getDepartmentInfo() throws DaoException{
Connection connection = null;
PreparedStatement pStatement = null;
HashMap<Integer,String> depaMap = new HashMap<Integer,String>();
int depId = 0;
String depName = null;

try {
connection = this.getConnection();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
pStatement = connection.prepareStatement(SEARCH_ALL_DEPARTMENT);
ResultSet resultSet = pStatement.executeQuery();
while(resultSet.next()){
depId  = resultSet.getInt(1);
depName = resultSet.getString(2);
depaMap.put(depId, depName);
pStatement.close();
pStatement.close();

}

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


return depaMap;

}}
当我 DepartmentDAO dd = new DepartmentDAO();
     dd.getDepartmentInfo();
的时候抛空指针异常,异常位置
datasource = (DataSource) servletContext.getAttribute("dataSource");connection = this.getConnection();请教问题出在哪?如何解决?我应该补充哪些知识点以避免下次犯类似错误?
先谢过!

解决方案 »

  1.   

    本人菜鸟一个 前几天也遇到了空指针异常...不过应该抛出了异常的行号吧  对应着找就行了  实在不行就添加一个  System.out.println("OK")  来看到底哪里错了  我就是这样找错的  楼主耐心找找
      

  2.   

    = =!你都学到servlet了,在学javase的时候debug技能还没学会吗?
      

  3.   

    在ServletContext里面存数据库的连接对象??我还没学ssh,楼下能解释下这种做法合理吗?就我所学应该写个jdbcutil才对。
      

  4.   

    我用的是连接池,写个listener,应用启动时,将连接池的source对象保存到servletsontext中,可以减少开销。
    jdbcutil可以做,但是……没我这种方式好