Metawerx Java Hosting Small Logo

JNDI - Java Naming and Directory Interface

JNDI enables a Java program or JSP page to reference resources specified in or outside the application.

JNDI names are specified as a URI. They point to anything from simple strings to complex data structures such as a JDBC data source.

For example, here is a JSP <sql:query> tag that uses JNDI to access a data source. The data source object has a JNDI address of java:comp/env/jdbc/mydatabase. In JSP, this can be refered to simply as jdbc/mydatabase.

<sql:query var="result" dataSource="jdbc/mydatabase">
    SELECT product_id, name, price FROM products
</sql:query>

The following example references the same information using Java, which uses the full JNDI URI.

DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mydatabase");

For both of the examples given above, the actual JDBC data source information is defined in META-INF/context.xml as a JNDI Resource.

JNDI Resources can be defined in:

  • server.xml in the <Context> tag
  • context.xml in the <Context> tag, as Resources (prefered)
  • web.xml as environment variables using the <env-entry> tag, although this is only useful for simple values

An example context.xml is displayed below, containing a single JNDI Resource, of the type javax.sql.DataSource.

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Resource name="jdbc/mydatabase" 
              auth="Container"
              type="javax.sql.DataSource" 
              username="YOUR_USERNAME" 
              password="YOUR_PASSWORD"
              driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://mysql.metawerx.net:3306/YOUR_DATABASE_NAME?autoReconnect=true"
              validationQuery="select 1"
              maxActive="10" 
              maxIdle="4"/>
</Context>

More information

navigation
metawerx specific
search
Share
tools
help

referring pages

Share