JNDI
1.What is JNDI
JNDI is Java Naming and Directory Interface. When developer needs to operate the DB in application, he/she doesn’t need to write DB url, user name, password etc in code with the help of JNDI. All developer needs to do is use name to map to DB.
2.How to do
2.1.Code
Context ctx = null; Connection con = null; try { ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("java:/comp/env/jdbc/testJNDI"); con = ds.getConnection();
For connecting to DB, name “java:/comp/env/jdbc” is fixed, data source name is developer/deployer defined, e.g. testJNDI in this example.
2.2.Configuration
The configuration can be placed in 3 places :
2.2.1.application META-INF/context.xml
<?xml version='1.0' encoding='utf-8'?> <Context> <Resource name="jdbc/testJNDI" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/test" username="root" maxActive="10" maxIdle="3" minIdle="1" maxWait="100" /> </Context>
The resource name is part of java:/comp/env/jdbc/testJNDI which described in 2.1.
2.2.2.server(e.g. Tomcat) conf/context.xml
The configuration is the same as 2.2.1.
2.2.3.server(Tomcat) conf/server.xml and context.xml
In this case, context.xml looks like :
<ResourceLink name="jdbc/testJNDI" global="jdbc/MyDB" auth="Container" type="javax.sql.DataSource"/>
and server.xml is :
<Resource name="jdbc/MyDB" global="jdbc/MyDB" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/test" username="root" maxActive="10" maxIdle="3" minIdle="1" maxWait="100" />
Note that the global value of context.xml is the value of resource name of server.xml.