javax.naming.NoInitialContextException using JNDI

喜欢而已 提交于 2019-12-11 05:16:15

问题


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:

See my code :

    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();
    }

And the error message :

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)

回答1:


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);

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>

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

Hope it helps



来源:https://stackoverflow.com/questions/13267891/javax-naming-noinitialcontextexception-using-jndi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!