I tried several different ways such that Tomcat loads the MySQL drivers when running my web application. I'm using Ubuntu 8.04, and the libraries come from the libmysql-java package. They are located in the directory shown below:

~$ ls /usr/share/java/mysql*
/usr/share/java/mysql-connector-java-5.1.5.jar

My CLASSPATH includes this file:

~$ echo $CLASSPATH
.:/usr/lib/jvm/java-6-sun/bin:/usr/local/tomcat/lib/servlet-api.jar:/usr/share/java/mysql-connector-java-5.1.5.jar

I even put a copy of the .jar file in my WEB-INF/lib/ directory in my web app:

/usr/local/tomcat/webapps/ohms/WEB-INF/lib$ ls
mysql-connector-java-5.1.5.jar

After making these changes, I restart Tomcat, re-compile my classes, restart Tomcat again. Also, I am importing the necessary libraries using import java.sql.*;

However I am still getting the java.lang.ClassNotFoundException: com.mysql.jdbc.Driver error when it runs the line Class.forName("com.mysql.jdbc.Driver").newInstance();

What am I doing wrong here?

Tomcat does not use the CLASSPATH in the webapp's classloader. You can add paths and files to the common.loader line in conf/catalina.properties. The classloader should have found the class when the jar was in WEB-INF/lib. I can't explain why it hasn't. If you are using 5.5, you can place the jar in common/lib or lib/ if you're using tomcat6. This path is loaded by a higher level classloader and should be picked up first.

Is it your app that's throwing the exception, or is it Tomcat itself?

Since you're using Class.forName(), I'm guessing that you're not also doing a JNDI config in Tomcat itself, but I'll throw this possibility out there anyway. For JNDI, Tomcat needs to be able to see the driver too, and it can't see JARs that you put in your app's WEB-INF/lib directory. If you put your driver in Tomcat's common lib directory, then Tomcat can see it, and your app can see it too. The directories are the ones that David mentions.

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.