Java Naming and Directory Interface (JNDI)
Using JNDI, applications running in distributed environment, helps to look up services independently.
How JNDI is useful?
- During deployment sequence, the same JNDI name can be used in different servers.
- It helps to provide security of credential leakage to the user groups like developer, testers, stagers etc, because the credentials are configured in the server not in the application.
- Connection Pooling can be achieved
How to use JNDI?
In order to use, JNDI classes and service providers should be there
The service provider may be :
- Lightweight Directory Access Protocol (LDAP)
- Common Object Request Broker Architecture (CORBA)
- Common Object Services (COS) name service
- Java Remote Method Invocation (RMI) RegistryThe objects needs to be created and registered so that , they can be further used for lookup.
How to configure JNDI in tomcat?
In tomcat environment we can configure JNDI in 3 different places
1. Inside the application using context.xml in META-INF directory.
2. Inside the tomcat server context.xml : Inside the apache-tomcat/conf directory we can configure. This can be helpful when multiple application needs the same database.
3. Both in server.xml and context.xml
NB: The database driver jar should be present in the tomcat lib directory
<Resource name="jdbc/lookupName" global="jdbc/lookupName" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/hdi" username="hiuser" password="hiuser" maxActive="100" maxIdle="20" minIdle="5" maxWait="10000"/>
In order to use it in java program we have to use the followng
DataSource ds = (DataSource) ctx.lookup(“java:/comp/env/jdbc/lookupName”);