Maven Jetty Plugin JNDI JDBC / DBCP configuration

Yesterday,I literary spent almost 5 hours just to get JNDI DBCP working properly with maven jetty plugin.
Previously I used tomcat6 ,but I noticed that using maven/jetty I can save lot of deployment time during development. So same as lots of other guys struggled with this problem …it gave me a real pain for too long.. So I thought it would be nice to write a blog just in case this might helpful to anyone out there.

In short here are the important points:

1) JNDI configuration : Like META-INF/context.xml in Tomcat ; jetty uses WEB-INF/jetty-env.xml (There are other ways like configure in the jetty-server.xml , but i am not going to discuss them here since my idea is to simply move the project between tomcat and jetty)

Here is the jetty-env.xml:
<?xml version=”1.0″?>

<!DOCTYPE Configure PUBLIC “-//Mort Bay Consulting//DTD Configure//EN” “http://jetty.mortbay.org/configure.dtd”&gt;

<Configure class=”org.mortbay.jetty.webapp.WebAppContext”>

<New id=”immunodb” class=”org.mortbay.jetty.plus.naming.Resource”>
<Arg>jdbc/ImmunoDB</Arg>

<Arg>

<New class=”org.apache.commons.dbcp.BasicDataSource”>

<Set name=”driverClassName”>com.mysql.jdbc.Driver</Set>

<Set name=”url”>jdbc:mysql://localhost:3306/ImmunoDB</Set>

<Set name=”username”>root</Set>

<Set name=”password”>immuno</Set>

</New>

</Arg>
</New>

</Configure>

Note that theres only two <Arg> arguments here ,and if you went through Jetty JNDI Documentation you might find you need to put 3 <Arg> tags.
This depends on the number of arguments in the constructor of “org.apache.commons.dbcp.BasicDataSource”,which changes with the jetty/jetty-maven-plugin version you use.

2) Jetty/Jetty-Maven version:
In POM add the jetty-maven-plugin , I prefer version 6.9.1,since in some versions there’s a bug which JNDI resources are not getting registered properly.

<build>

<plugins>

<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.9</version>
</plugin>
</plugins>
</build>

3) I case of JDBC/DBCP , put your jdbc-driver.jar and apache-dbcp.jars in the POM dependencies.
With tomcat you have to put these jars in $TOMCAT/libs folder (wont work if they are in WEB-INF/libs) , but in jetty you can put them in WEB-INF/libs.

Thats it..now u can access you JNDI source as follows”

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup(“java:comp/env”);
DataSource ds = (DataSource)
envCtx.lookup(“jdbc/ImmunoDB”);

Hope this helps.