java 如何将 JDBC 驱动程序导入动态 Web 项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30384473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:02:17  来源:igfitidea点击:

How to import JDBC driver into Dynamic Web Project?

javamysqltomcatservletsjdbc

提问by giliev

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.

我有一个本地 MySQL 数据库。当我创建一个简单的 Java 项目,其中一个类只包含 main 时,我成功地使用 JDBC 连接器 jar 从数据库中检索了一些数据,使用 Build path -> Add external jars 导入,并且它完美地工作。

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.

然后我尝试使用类似的方法,但现在在使用 Servlet的动态 Web 项目中,但我得到java.sql.SQLException: No合适的驱动程序找到 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:

我一直在寻找类似问题的答案几个小时,到目前为止,这是我尝试放置 JDBC MySQL 连接器的地方:

  1. Directly into Java Resources folder
  2. Into lib folder which is within Java Resources
  3. Into WebContent/WEB-INF/lib/
  1. 直接进入Java Resources文件夹
  2. 进入 Java 资源中的 lib 文件夹
  3. 进入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.

我需要 web.xml 还是 context.xml?我阅读了使用它们的教程,尝试实现所解释的示例,但我仍然遇到同样的问题。

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

我正在 Linux Mint 17 上工作,将 Tomcat 7 用于 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:

以及我试图运行的 servlet:

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
    }

}

回答by Roberto Linares

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

在 eclipse 项目中有两种使用和引用 jar 文件的方法。

  • One is at compile timeand 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.

  • 一种是在编译时用于编译目的。要使您的项目编译,您需要在类路径中添加所需的库。在 Eclipse 中,右键单击您的项目,将鼠标悬停在“构建路径”上,然后选择“配置构建路径”。在对话框中转到“库”选项卡,在那里您可以看到您拥有哪些 jars/库。如果需要添加更多内容,可以使用对话框右侧的按钮。在那里您应该选择“添加外部 jars”并从您的文件系统中选择 MySql JDBC 驱动程序。

  • 另一种是在运行时。这是将 Web 应用程序部署到应用程序服务器的时间。现在,每次您的应用程序需要从外部 jar 加载一个类时,它都会在应用程序服务器的类加载器中查找该 jar。类加载器包含应用程序服务器、已配置资源和已部署应用程序中 WEB-INF/lib/ 文件夹中可用 jar 文件的路径。您可以配置类加载器首先检查的位置。

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.

在您非常具体的情况下,您需要在任何类加载器路径中添加 MySQL JDBC 驱动程序(因为我假设您的项目已经编译),以便您可以将 jar 添加到 Tomcat 的 /lib 目录或应用程序的 /WEB-INF/lib / 目录。之后只需重新部署或重新启动 tomcat,您应该能够使用 MySQL JDBC 连接。

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:

此外,在使用 DriverManager 接口创建 JDBC 连接时,请记住始终首先创建 JDBC 驱动程序的实例,以便将其加载到类加载器中。您可以在MySQL JDBC 驱动程序文档中看到这一点。Ej:

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

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.

在使用之前调用此行DriverManager.getConnection(...),您现在应该能够创建和使用您的 JDBC 连接。

回答by hooknc

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

您的 mysql jdbc 驱动程序应该放在您的 tomcat 目录中:

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

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.

确保在将新的 mysql jdbc 驱动程序 jar 文件放在那里后启动/重新启动服务器。

回答by Codemaker

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

只需将您的驱动程序 jar 文件放入 WEB-INF/lib 文件夹中。