t7bdh3hdhb
t7bdh3hdhb

Reputation: 438

JNDI lookup in servlets init method with property load-on-startup

I have a Servlet which initializes its DataSource in the Servlets init method (because it is accessed there the first time). When the servlet is getting loaded I get the following exception message

Cannot create JDBC driver of class '' for connect URL 'null'

But when the first request is processed the jndi lookup works fine and the DataSource is initialized properly.

Here is my DataSource class:

public class PostgresDataSource{

private static DataSource dataSource;

static {
    try {

        dataSource = (DataSource) new InitialContext().lookup("java:/comp/env/jdbc/somedb");

    } catch (NamingException e) {
        Log.logger.fatal("Failed to initialize DB!");
        Log.logger.error(e.getMessage());
        e.printStackTrace();
    }
}

public static Connection checkOut(){
    if ( dataSource != null )
    {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            Log.logger.error("Failed to establish DB connection!");
            Log.logger.error(e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
    else
    {
        Log.logger.error("Failed to check out DB-Connection: Postgres DataSource not initialized!");
        return null;
    }
}

public static void checkIn( Connection dbcon){
    if ( dataSource != null )
    {
        try {
            dbcon.close();
        } catch (SQLException e) {
            Log.logger.error("Failed to close DB connection!");
            e.printStackTrace();
        }

    }
    else
    {
        Log.logger.error("Cannot check in DB-Connection: Postgres DataSource not initialized!");
    }
}
}

Anyone encountered the same problem? What's the reason for this and how to solve it?

Upvotes: 0

Views: 2008

Answers (1)

pundit
pundit

Reputation: 312

Instead of using dataSource = (DataSource) new InitialContext().lookup("java:/comp/env/jdbc/somedb");

Please use the following, this may solve the problem

        InitialContext context = new InitialContext();
        Context envCtx = (Context) context.lookup("java:comp/env");
        dataSource = (DataSource) envCtx.lookup("jdbc/somedb"); 

Upvotes: 1

Related Questions