Monday, September 19, 2005

Adding a JNDI Datasource to Tomcat 5.5.9

By using a JNDI data source to connect to a database from a web application running on tomcat, you do not have to care about connections building, closing, or pooling anymore.

Defining a JNDI data source

I assume that your web application is named 'myWebApp' and accesses a database named 'myDatabase' on a MySql server 'localhost'.
Create a new xml file named 'myWebApp.xml' in the directory {TOMCAT_HOME}/conf/Catalina/localhost and add the following content to it:
<context path="/myWebApp" docbase="myWebApp" debug="5" reloadable="true" crosscontext="true">

<logger classname="org.apache.catalina.logger.FileLogger" prefix="localhost_myWebApp_log." suffix=".txt" timestamp="true">

<!-- org.apache.commons.dbcp.BasicDataSourceFactory -->

<resource name="jdbc/myDatabase" auth="Container" type="javax.sql.DataSource" factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory" username="guru" password="secret" driverclassname="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/myDatabase?autoReconnect=true" maxwait="1000" removeabandoned="true" maxactive="30" maxidle="10" removeabandonedtimeout="60" logabandoned="true">

I use the DataSourceFactory org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory and not org.apache.commons.dbcp.BasicDataSourceFactory as it is recommended on the Jakarta project web page for the simple reason that it does not work.

Adding required libraries

Download the MySql jdbc connector mysql-connector-java-3.0.16-ga-bin.jar and move it to {TOMCA_HOME}/common/lib

Accessing the data source

From a jsp site you can now access the database using the following JSTL code:

<sql:query var="rs" dataSource="jdbc/myDatabse">




Post a Comment

<< Home