Wednesday, May 6, 2009

GWT 1.6 - Using a JNDI Datasource

With the update to GWT 1.6 we found that our JNDI connections would no longer work. This was due to GWT 1.6 using Jetty instead of Tomcat as the embedded server. After searching online we found very few documents or posts explaining how to use a JNDI DataSource with GWT. The problem with most of these methods was that they required you to rewrite some of the Java code. Continuing to research Jetty the following solution was found that requires a few simple modifications to the project.

Configure the DataSource:

To do this you will need to configure a jetty-web.xml file and place it in your Web Application’s WEB-INF directory. Details on how to do this for various databases are located on the Jetty Documentation site at http://docs.codehaus.org/display/JETTY/DataSource+Examples.

NOTE: I believe the version of jetty shipped with GWT is below 6.1.12 and therefore you must leave off the first parameter in the example docs as it was added in jetty 6.1.12rc3. See the note at the top of the Jetty documents page.

A Sample jetty-web.xml file for connecting to a local mysql server follows:


<?xml version=”1.0”?>
<!DOCTYPE Configure PUBLIC “-//Mort Bay Consulting//DTD Configure//EN” http://jetty.mortbay.org/configure.dtd>

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

        <New id=”website” class=”org.mortbay.jetty.plus.naming.Resource”>

                <Arg>java:comp/env/jdbc/database</Arg>
                <Arg>
                        <New class=”com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource”>
                                <Set name=”Url”>jdbc:mysql://localhost:3306/database</Set>
                                <Set name=”User”>(Username)</Set>
                                <Set name=”Password”>(Password)</Set>
                        </New>
                </Arg>
        </New>

</Configure>


Configure the Eclipse Run Configuration:

Open the Eclipse run configuration and select the “Arguments” Tab. Then under “VM arguments“ section add the following:


-Djava.naming.factory.initial=org.mortbay.naming.InitialContextFactory


Acquire a Database Connection:

You should now be able to make a JNDI lookup to retrieve the datasource:

public Connection retrieveConnection() throws Exception {
        Connection lConnection = null;

        Context lContext = new InitialContext();
        DataSource lDataSource = (DataSource) lContext.lookup("java:comp/env/jdbc/database");
        lConnection = lDataSource.getConnection();

        return lConnection;                
}




Resource Injection:

Supposedly Jetty supports the servlet 2.5 specification and resource injection via the web.xml entry or @resource annotation. However, I have yet to figure out if this is supported by the Jetty version shipped with GWT. If anyone has figured out whether or not this works and if so how it is done please let me know.