使用JNDI的javax.naming.NoInitialContextException [英] javax.naming.NoInitialContextException using JNDI

查看:97
本文介绍了使用JNDI的javax.naming.NoInitialContextException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Iam trying to connect mysql by using JNDI. But it show an exception

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)

推荐答案

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

usually you need to specify where to get the InitialContext from (and where is located the jndi tree you will use)

您可以通过两种方式进行操作:

You can do it in two ways :

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并将其放在您的类路径中:

or create a jndi.properties and place it in your classpath :

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服务器).

In your case it is complaining because the lack of INITIAL_CONTEXT_FACTORY (which depends on which Java EE server you are using).

希望有帮助

这篇关于使用JNDI的javax.naming.NoInitialContextException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆