JNDI InitialContext not working in simple netbeans

2019-07-30 14:18发布

问题:

Warning: New to Java

I have a simple Netbeans project - I wanted to just learn about interacting with DB's coming from php I thought I would have a go with a local one running on my computer.

Lots of the examples out there say to use the InitialContext() object to refer to the database resource.

After following the examples I get the following exception - Lots of Google stuff points to some .xml file - which I have no idea about or even where it exists in the Netbeans project? I'm not using a Webserver at this time so not Tomcat or anything like that, just local Java program to do this, I suspect this might be the problem. Could anyone shed some light on this?

Exception thrown 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.


package learningjava;
import com.mysql.jdbc.jdbc2.optional.*;
import com.mysql.jdbc.Driver;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.*;



public class LearningJava {

    public static void main(String[] args) {

       MysqlDataSource test_db = new MysqlDataSource(); 

       test_db.setServerName("localhost");
       test_db.setDatabaseName("dev");

       try {

            InitialContext test_db_context = new InitialContext();
            test_db_context.bind("jcdb/testdb", test_db);
            MysqlDataSource test_db_datasource = (MysqlDataSource)test_db_context.lookup("testdb");

       } catch (NamingException e) {

           System.out.println("Exception thrown " + e);

       }
        try {

            test_db.getConnection("root","password");

        } catch (SQLException e) {

             System.out.println("Exception thrown " + e);

        }


    }    

}

回答1:

In general you should understand that JNDI should have a server. In a code snippet you've provided you're using a _CLIENT_SIDE_ part of JNDI technology when you're doing your lookup. There should be a JNDI server that should be accessible from your local client connection. Once configured properly, the call to lookup should issue a connection with JNDI server and provide a way to obtain/bind resources to that server.

How to configure JNDI properly?

Usually you should supply a properties file that will contain a host name of this server, a port + some implementation specific information.

JNDI server is usually already provided when you're using application server (like JBoss or Web Sphere). I think this is the root of misunderstanding here.

Hope, this helps



回答2:

could you try to add this before the InitialContext test_db_context = new InitialContext();:

System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");

You should include the jar naming-common-4.1.34 and mysql-connector-java-5.1.6 in your classpath

This example works for me (not optimized but works!)

public static void main(String[] args) throws NamingException {
        // Create initial context
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");

        InitialContext ic = new InitialContext();
        ic.createSubcontext("java:");
        ic.createSubcontext("java:comp");
        ic.createSubcontext("java:comp/env");
        ic.createSubcontext("java:comp/env/jdbc");

         MysqlConnectionPoolDataSource mysqlConnectionPoolDataSource = new MysqlConnectionPoolDataSource();
         mysqlConnectionPoolDataSource.setUser("root");
         mysqlConnectionPoolDataSource.setPassword("root");
         mysqlConnectionPoolDataSource.setURL("jdbc:mysql://localhost:3306/test_my_database");

         ic.bind("java:comp/env/jdbc/test", mysqlConnectionPoolDataSource);

    }


回答3:

Usually JNDI is used inside an application server which is not your case.

For your needs you may use the following code:

Class.forName("com.mysql.jdbc.Driver")
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/dbname", "user", "password");

Also you need to download MySQL driver here and add corresponding JAR file (mysql-connector-java-5.1.21-bin.jar) to your application's class path here is described how to do it.