我尝试了相关问题的许多可用答案,但没有一个成功。
这是我的问题
我有一个动态 Web 应用程序,它使用 Oracle 数据库来检索数据。为了让它变得更好,我使用 db.properties 配置文件并创建数据源,
这是 dataFactory.class 的代码:
public DataSource getDatasource() {
Properties props = new Properties();
FileInputStream fis = null;
InputStream in = null;
OracleDataSource oracleDS = null;
try {
fis = new FileInputStream("db.properties");
props.load(fis);
oracleDS = new OracleDataSource();
oracleDS.setURL(props.getProperty("url"));
oracleDS.setUser(props.getProperty("user"));
oracleDS.setPassword(props.getProperty("password"));
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return oracleDS;
}
为了建立连接,我在 EmployeeDao.class 中使用它,
DataSource ds;
EmpDatasourceFactory empDs = new EmpDatasourceFactory();
Connection conn;
public boolean insertRecord(Employee emp) {
boolean status = false;
ds = empDs.getDatasource();
try {
conn = ds.getConnection(); //Getting the null point exception
}
}
注意:请注意,我有必要的所有其他代码。
问题是,当我创建一个 java 文件并创建一些方法并使用它来建立连接时,它工作正常,我的意思是当它作为 java 应用程序运行时。
但是当使用employeeDao.java并使用apache tomcat服务器运行它时,它给了我一个错误。请帮忙。!!!
最佳答案
在@joop Eggen的帮助下,我能够修复这个错误,最后我的方法看起来像
public static DataSource geDataSource() throws ResourceResolverException{
ResourceBundle props = ResourceBundle.getBundle("db");
OracleDataSource oracleDS = null;
try {
oracleDS = new OracleDataSource();
oracleDS.setURL(props.getString("url"));
oracleDS.setUser(props.getString("user"));
oracleDS.setPassword(props.getString("password"));
} catch (SQLException e) {
e.printStackTrace();
}
return oracleDS;
}
我必须处理所有的“ResourceResolverException”。之后效果很好。
快乐编码..!!!并使其成为 Java :)
关于java - db.properties - 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25567687/