记录一次奇妙的Debug之旅
我在tomcat连接数据库时,一直报500空指针错误,查的时候很多人说是缺少了jar包,根据他们说的讲mysql的驱动放在了tomcat的lib及项目web下的lib均失效,数据库连接本地测试也没有问题,后来终于在教程某个弹幕中发现了问题所在
public static Connection getConnection(){
Connection conn = null;
PreparedStatement ps = null;
try {
//1.加载配置文件
//InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
//2.读取配置信息
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
//3.加载驱动
Class.forName(driverClass);
//4.获取连接
conn = DriverManager.getConnection(url,user,password);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return conn;
}
原来的代码为第六行注释部分,调用系统加载器,载入配置文件,当web项目运行时,IDE编译器会把src下的一些资源文件移至WEB-INF/classes,classPath目录其实就是classes目录。这个目录下放的一般是web项目运行时的class文件、资源文件(xml,properties…);
故而应该调用类的加载器JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
Q.E.D.