简体   繁体   English

带有属性load-on-startup的servlets init方法中的JNDI查找

[英]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). 我有一个Servlet,它会在Servlet的init方法中初始化其DataSource(因为它是第一次在此访问)。 When the servlet is getting loaded I get the following exception message 加载servlet时,出现以下异常消息

Cannot create JDBC driver of class '' for connect URL 'null' 无法为连接URL'null'创建类''的JDBC驱动程序

But when the first request is processed the jndi lookup works fine and the DataSource is initialized properly. 但是,当处理第一个请求时,jndi查找工作正常,并且数据源已正确初始化。

Here is my DataSource class: 这是我的DataSource类:

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? 这是什么原因以及如何解决?

Instead of using dataSource = (DataSource) new InitialContext().lookup("java:/comp/env/jdbc/somedb"); 而不是使用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"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM