Search code examples
javaweb-applicationsjdbcdatasourcetomcat6

db.properties - null pointer exception


I tried many available answers for related question but none of them was success.

Here's my problem,

I'm having a dynamic web application and it uses oracle database to retrieve data. To make it nice I'm using a db.properties config file and making a datasource,

Here's the code for 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;
}

and to make a connection I'm using it in 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
    }
}

Note: Please note that I'm having all other codes as necessary.

And The problem, When i make a java file and make some methods and use this to make a connection it works fine, i mean when running it as a java application.

But when using for a employeeDao.java and run it using apache tomcat server it gives me an error. Please help.!!!


Solution

  • A .war (a zip file like a .jar) is the normal way to deploy a web application. Inside a zip one cannot use File to retrieve a zip entry.

    The way to go, is reading a "resource" - from the class path. ResourceBundle is appropriate here.

    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;
    

    Other practices are to define such application resources outside the .war, in the web container. This is a bit different per Java EE application server, but for instance allows using different data sources for different servers.