2014-08-29 18 views
1

我嘗試了許多可用的相關問題的答案,但沒有一個是成功的。db.properties - 空指針異常

這裏是我的問題,

我有一個動態的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服務器運行它時,它會給我一個錯誤。請幫忙。!!!

回答

0

.war(壓縮文件,如.jar)是部署Web應用程序的常用方式。在壓縮文件中,不能使用文件來檢索zip條目。

要走的路是從班級路徑讀取「資源」。 ResourceBundle在這裏適用。

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 (ResourceNotFoundException e) { 
    e.printStackTrace(); 
} catch (SQLException e) { 
    e.printStackTrace(); 
} 
return oracleDS; 

其他做法是在Web容器中的.war之外定義這樣的應用程序資源。每個Java EE應用服務器都有所不同,但是例如允許爲不同的服務器使用不同的數據源。

+0

那麼,經過一些修改後,工作。感謝那。 我已將我的方法包含在答案框中。謝謝。 – KingFeming 2014-09-01 05:32:52

+0

對於任何不知情的讀者,我已將「ResourceBundle.get」更正爲「ResourceBundle.getBundle」。 – 2014-09-01 07:16:53

+0

謝謝你@Joop Eggen – KingFeming 2014-09-01 09:56:38

1

隨着@joop埃根的幫助下,我才得以修復這個錯誤,最後我的方法看起來就像

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 :)