1

我正在尝试使用 JNDI 连接 mysql。但它显示了一个例外

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:

查看我的代码:

    VendorDataSource vds = new VendorDataSource();
    vds.setServerName("localhost");
    vds.setDatabaseName("jnditest");
    vds.setDescription("The data source for inventory and personnel");

    try {
            ctx = new InitialContext();
        ctx.bind("jdbc/myds", vds);

    } catch (NamingException e1) {

        e1.printStackTrace();
    }

    try {
        ctx = new InitialContext();
        DataSource ds = (DataSource)ctx.lookup("jdbc/myds");
        Connection conn = ds.getConnection("root", "password");

    } catch (NamingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

和错误信息:

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
    at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
    at javax.naming.InitialContext.bind(Unknown Source)
    at samplemariadb.DataSourceConnectivity.main(DataSourceConnectivity.java:33)
4

1 回答 1

2

通常您需要指定从何处获取 InitialContext(以及您将使用的 jndi 树的位置)

你可以通过两种方式做到这一点:

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, 
    "<initialContextFactory>");
env.put(Context.PROVIDER_URL, "<url>");
env.put(Context.SECURITY_PRINCIPAL, "<user>");
env.put(Context.SECURITY_CREDENTIALS, "<password>");
ctx = new InitialContext(env);

或创建一个 jndi.properties 并将其放在您的类路径中:

java.naming.factory.initial=<initialContextFactory>
java.naming.provider.url=<url>
java.naming.security.principal=<user>
java.naming.security.credentials=<password>

在您的情况下,它抱怨是因为缺少 INITIAL_CONTEXT_FACTORY (这取决于您使用的 Java EE 服务器)。

希望能帮助到你

于 2012-11-07T10:49:31.040 回答