Search code examples
eclipseservletsjdbcclassnotfoundexception

How to install JDBC driver in servlet based project without facing java.lang.ClassNotFoundexception


There is a VERY similar question to mine but in my case I don't have any duplicate jars in my build path, so the solution does not work for me. I've searched google for a couple of hours now, but none of the solutions I've found there actually resolve my issue. I'm creating a web site with some database connectivity for a homework. I'm using a MySQL database, developing in Eclipse and running on Windows.

I keep getting java.lang.ClassNotFoundException: com.mysql.jdbc.Driver with the following code:

import java.sql.*;
//...
public void someMethodInMyServlet(PrintWriter out)
{
    Connection connection = null;
    PreparedStatement query = null;
    try {

        out.println("Create the driver instance.<br>");
        Class.forName("com.mysql.jdbc.Driver").newInstance();

        out.println("Get the connection.<br>");
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "secret");
        query = connection.prepareStatement( "SELECT * FROM customers");

        //...
    } catch (Exception e)
    {
        out.println(e.toString()+"<br>");
    }
}
//...

When I run the above code I get the following output:

Create the driver instance.
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

It doesn't get past the Class.forName... line and I can't figure out why! Here is what I did:

  1. Download mysql-connector.
  2. Put it in my MySQL folder C:\Program Files\MySQL\mysql-connector-java-5.1.12\mysql-connector-java-5.1.12-bin.jar.
  3. Opened the project properties in Eclipse.
  4. Add External Jar to my Build Path and I selected mysql-connector-java-5.1.12-bin.jar.

Every time I attempt to use the servlet I get the same error regardless if I have the jar in there or if I don't. Could you help me figure this out?


Solution

  • As for every "3rd-party" library in flavor of a JAR file which is to be used by the webapp, just copy/drop the physical JAR file in webapp's /WEB-INF/lib. It will then be available in webapp's default classpath. Also, Eclipse is smart enough to notice that. No need to hassle with buildpath. However, make sure to remove all unnecessary references you added before, else it might collide.

    In case you're using Maven as dependency management tool, then it's sufficient to basically add Maven coordinates of the desired JDBC driver JAR file as a new <dependency> in project's pom.xml. It will eventually automatically end up in webapp's /WEB-INF/lib. In case of the MySQL JDBC driver you can find the coordinates here.

    An alternative is to install it in the server itself by dropping the physical JAR file in server's own /lib folder. This is required when you're using server-provided JDBC connection pool data source which in turn needs the MySQL JDBC driver. See also the following links.

    See also: