如何将JDBC驱动程序导入动态Web项目? [英] How to import JDBC driver into Dynamic Web Project?

查看:150
本文介绍了如何将JDBC驱动程序导入动态Web项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个本地MySQL数据库.当我创建一个简单的Java项目(其中一个类仅包含main)时,我使用JDBC连接器jar成功地从数据库中检索了一些数据,并通过Build path-> Add external jars导入了该文件,并且效果很好.

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.

然后,我尝试使用类似的方法,但是现在在一个动态Web项目中,我正在其中使用Servlet,但是却得到了 java.sql.SQLException:没有找到合适的驱动程序对于jdbc:mysql://localhost/ePay .

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.

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

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. 直接进入Java Resources文件夹
  2. 进入Java资源中的lib文件夹
  3. 进入WebContent/WEB-INF/lib/

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

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.

我正在使用Tomcat 7到Eclipse IDE中进行Linux Mint 17开发.

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

这是我的项目结构的照片:

Here is the photo of my project structure:

以下是相关的课程:

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);
    }
}

用户类别:

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;
    }

}

还有我要运行的servlet:

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
    }

}

推荐答案

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

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

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

  • 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.

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

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.

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

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.

更新:

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

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();

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

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

这篇关于如何将JDBC驱动程序导入动态Web项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆