05 February, 2016

Apache Tomcat JNDI mapping

Suppose that an intrepid Java developer is writing a web application that runs in Apache Tomcat, and that connects to a DBMS using a JNDI (Java Naming and Directory Interface) specification. And suppose that, instead of the usual Tomcat location for the JNDI entry—conf/context.xml—her manager has told her to put all application specific Tomcat configuration in conf/server.xml instead. How then does she make those JNDI entries visible to the app, without modifying any other Tomcat configuration files?

She does it by creating or editing META-INF/context.xml in the web app, with a <ResourceLink> whose name matches the JNDI <Resource> in the server.xml file.

Examples

Apache Tomcat conf/server.xml:

...
   <GlobalNamingResources>
    <Resource   name="jdbc/oraDataSource"
                description="Oracle JNDI Datasource"
                auth="Container"
                type="javax.sql.DataSource"
                driverClassName="oracle.jdbc.OracleDriver"
                url="jdbc:oracle:thin:@AMEDMRMCA4397.amed.ds.army.mil:1521:MRMCD"
                username="user"
                password="pass" />


    <Environment name="Common.Web.APPNAME" type="java.lang.String" value="WebAppName" />   
  </GlobalNamingResources>

...



Web app META-INF/context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE project>
<Context>
    <ResourceLink name="jdbc/oraDataSource" type="javax.sql.DataSource" global="jdbc/oraDataSource" />
    <ResourceLink name="Common.Web.APPNAME" type="java.lang.String" global="Common.Web.APPNAME" />
</Context> 



Without that magic mapping piece, she will probably get an error about 'no suitable driver' at the first attempt to open as a database session, and that may be frustrating to debug, and make her sad.

No comments:

Post a Comment