2

I have a local MySQL database. When I created a simple Java project, with one class which contained only main, I successfully retrieved some data from the database using JDBC connector jar, imported with Build path -> Add external jars, and it worked perfectly.

Then I tried to use a similar approach, but now in a Dynamic Web Project, in which I am using Servlets, but I get java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/ePay.

I have been looking for several hours into the answers of similar questions, and here is where I have tried to put the JDBC MySQL connector so far:

  1. Directly into Java Resources folder
  2. Into lib folder which is within Java Resources
  3. Into WebContent/WEB-INF/lib/

Do I need web.xml or context.xml? I read a tutorial in which they were used, tried to implement the explained example, but I still had the same problem.

I am working on Linux Mint 17, using Tomcat 7 into Eclipse IDE.

Here is the photo of my project structure:

enter image description here

Here are the relevant classes:

package dbObjects;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Entity {
    protected Connection getConnection() throws SQLException {
        String pass = "mypass";
        String userDB = "root";
        Connection conn = DriverManager.getConnection(
                "jdbc:mysql://localhost/ePay", userDB, pass);
        return conn;
    }

    protected ResultSet getResultSet(String sql) throws SQLException {
        Connection conn = getConnection();
        Statement st = conn.createStatement();
        return st.executeQuery(sql);
    }
}

The user class:

package dbObjects;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

public class User extends Entity {
    private long idUser;
    private String userName;
    private String pass;
    private String fullName;
    private String email;
    private Date dateOfBirth;
    private String address;

    public User(long idUser, String userName, String pass, String fullName,
            String email, Date dateOfBirth, String address) {
        super();
        this.idUser = idUser;
        this.userName = userName;
        this.pass = pass;
        this.fullName = fullName;
        this.email = email;
        this.dateOfBirth = dateOfBirth;
        this.address = address;
    }

    public User(long idUser) throws SQLException {
        super();
        this.idUser = idUser;
        setUserById(idUser);
    }

    private void setUserById(long idUser) throws SQLException {
        ResultSet resultSet = getResultSet("SELECT * FROM User WHERE idUser = " + idUser);
        while(resultSet.next()) {
            System.out.println(resultSet.getInt("idUser"));
            userName = resultSet.getString("username");
            pass = resultSet.getString("pass");
            fullName = resultSet.getString("fullname");
            email = resultSet.getString("email");
            dateOfBirth = resultSet.getDate("dateOfBirth");
            address = resultSet.getString("address");
        }
    }

    @Override
    public String toString() {
        return userName;
    }

}

And the servlet which I am trying to run:

package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dbObjects.User;

/**
 * Servlet implementation class HomeServlet
 */
@WebServlet(description = "Home page shown to user", urlPatterns = { "/HomeServlet" })
public class HomeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public HomeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        User user = null;
        try {
            user = new User(1);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        PrintWriter pw = response.getWriter();
        pw.println(user);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}
giliev
  • 2,938
  • 4
  • 27
  • 47
  • Why don't you try to create a Maven project? – Fernando Garcia May 21 '15 at 21:19
  • @FernandoGarcia I don't have experience with web development. I need simple web app, I googled and it seemed to me like the easiest way for creating a web app. I need it for a school project, which primary goal is not implementing a web app, I need the app just to show the results :) Any advice is very welcome. – giliev May 21 '15 at 21:23

3 Answers3

8

There are two ways to use and reference a jar file in an eclipse project.

  • One is at compile time and for compilation purposes. To make your project compile, you need to add your required libraries in the classpath. In eclipse, right click to your project, hover on 'Build Path', then select 'Configure Build Path'. In the dialog go to 'Libraries' tab and there you can see which jars/libraries you have. If you need to add more, you can use the buttons at the right side of the dialog. There you should select 'Add external jars' and select the MySql JDBC Driver from your file system.

  • The other one is at run time. This is when you deploy your web application to an application server. Now everytime your application needs to load a class from an external jar, it will look for the jar in the application server's class loader. The classloader conatins the paths to the available jar files in your application server, in configured resources and in your deployed application in the WEB-INF/lib/ folder. You can configure which place the classloader will check first.

In your very specific case, you need to add the MySQL JDBC Driver in any of classloader paths (since I asume your project compiles already) so you can either add the jar to Tomcat's /lib directory or to your application's /WEB-INF/lib/ directory. After that just redeploy or restart tomcat and you should be able to use MySQL JDBC connections.

UPDATE:

Also, when using a DriverManager interface to create a JDBC Connection, remember to always create an instance of your JDBC driver first in order to load it into your Classloader. You can see this in the MySQL JDBC Driver documentation. Ej:

Class.forName("com.mysql.jdbc.Driver").newInstance();

Call this line before using DriverManager.getConnection(...) and you should now be able to create and use your JDBC Connections.

Roberto Linares
  • 2,215
  • 3
  • 23
  • 35
  • I added a picture of my project structure. I copy-pasted the MySQL JDBC jar into WEB-INF/lib directory, which imported it into Web App Libraries, but I still have the same problem. Any idea what I may be the problem? – giliev May 22 '15 at 12:54
  • Can you also add the source code where you create the JDBC connection? – Roberto Linares May 22 '15 at 14:35
  • Edited, the connection is made in Entity class. I don't use any .xml so far. I followed a tutorial in which no .xml was used, so I am trying to retrieve some data without using any configuration files. Is that possible? – giliev May 22 '15 at 14:52
  • 1
    Check the update in my answer. I think your problem is in the code where you create the connection. – Roberto Linares May 22 '15 at 15:05
  • Thank you very much! I previously successfully retrieved data in a simple Java project (not a web project), without calling the Class.forName(...), so I had no idea that the error is in the code. You saved my day! Thanks :) – giliev May 22 '15 at 15:15
2

Your mysql jdbc driver should be placed into your tomcat's directory:

catalina_base/webapps/app_name/WEB-INF/lib/

Make sure to start/restart your server after placing your new mysql jdbc driver jar file there.

hooknc
  • 4,854
  • 5
  • 31
  • 60
-1

just place your driver jar file into WEB-INF/lib folder.

Codemaker2015
  • 12,190
  • 6
  • 97
  • 81