MySQL and DBCP for Tomcat 5
I find that between each version of Tomcat working totally differently and the fact that the documentation is wildly inconsistent and often misleading setting up a connection pool on Tomcat can be a big headache. On top of everything else I found when Googling that you get all these hits that aren't always totally useful or point you at the documentation that's not quite all there in the first place. Now that I got a DBCP pool up and working on Tomcat 5.5 with MySQL I thought I'd describe it here.
So if you're looking for help with a Tomcat 5.5 DBCP and MySQL connection pool you are in the right place. If you have another Tomcat version sorry but you're likely out of luck. Again different versions have different ways of doing all this.
Step One - Get all the Jars in the right place
You need two jars for a DBCP connection pool with MySQL. One is the DBCP jar called naming-factory-dbcp.jar. Tomcat seems to ship with this now so you should have it. It should be in CATALINA_HOME/common/lib
The second jar is a MySQL connector jar with the MySQL JDBC driver. When you download this jar make sure you download the correct (aka non debugging) driver. This jar also goes into CATALINA_HOME/common/lib
Step Two - configure your context
There are a couple of ways to configure your context (see the Tomcat docs for alternatives) but the way I will describe here is to create your own context.xml. This goes into your META-INF directory in your project, WAR and when deployed. For this example imagine the context is named DBTest and in a similarly named code base. Here are the contents for your context
Step Three - configure your web.xml
You need to add the following to the web.xml for your application. This snippet goes inside the web-app element of your web.xml.
Step Four - write some testing code
Here is a small snippet of code showing how to get a java.sql.Connection using what has been defined above. Note how the name above "jdbc/mypool" is translated into one we can lookup from the InitialContext.Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:/comp/env/jdbc/mypool");
Connection conn = ds.getConnection();
Step Five - Deploy
You can now build and deploy your web application to Tomcat 5.5 and you should now have a functional DBCP connection pool running to MySQL.
I hope this helps someone, I think it would have helped me.
|© 2008 Max Stocker|