java 如何将一个简单的 Servlet 与 JDBC 结合起来?代码导致 ClassNotFoundException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15606425/
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-10-31 20:14:06  来源:igfitidea点击:

How to combine a simple Servlet with JDBC? Code results in ClassNotFoundException

javamysqlservletsjdbcclassnotfoundexception

提问by izza

I have written a simple JDBC and it works well (I run it in command prompt using java and javac).

我编写了一个简单的 JDBC,它运行良好(我使用 java 和 javac 在命令提示符下运行它)。

I also have written a simple HelloworldServlet and it works well (using Apache Tomcat 7.0). I access the servlet using browser, http://www.myhost.com:8088/projecthello/servlethello, and it displays the Helloworld.

我还编写了一个简单的 HelloworldServlet,它运行良好(使用 Apache Tomcat 7.0)。我使用浏览器http://www.myhost.com:8088/projecthello/servlethello访问 servlet ,它显示 Helloworld。

Now I'm trying to combine a simple servlet and JDBC. I want to make a query SELECT to a table, and display it in my browser using this URL: http://www.myhost.com:8088/projectmovie/directors-view

现在我正在尝试结合一个简单的 servlet 和 JDBC。我想查询 SELECT 到一个表,并使用这个 URL 在我的浏览器中显示它:http://www.myhost.com: 8088/projectmovie/ directors-view

In folder /WEB-INF/classes, I have 2 files: DirectorsViewServlet.java and DirectorSelect.java

在文件夹 /WEB-INF/classes 中,我有 2 个文件:DirectorsViewServlet.java 和 DirectorSelect.java

Here's DirectorsViewServlet.java:

这是 DirectorViewServlet.java:

 import java.io.*;
 import javax.servlet.*;
 import javax.servlet.http.*;
 import java.sql.*;

 public class DirectorsViewServlet extends HttpServlet {

  public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    DirectorSelect ds = new DirectorSelect();
    out.println(ds.selectDirectors());
  }

  public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    doGet(req, res);
  }

}

And here's the DirectorSelect.java:

这是 DirectorSelect.java:

 import java.sql.*;

 class DirectorSelect{
  public String selectDirectors() {
    Connection koneksi = null;
    Statement stat = null;
    String str = "";
    try{
        Class.forName("com.mysql.jdbc.Driver");
        koneksi = DriverManager.getConnection("jdbc:mysql://localhost/dbizza","root","");
        stat = koneksi.createStatement();
        ResultSet hasil = stat.executeQuery("SELECT * FROM directors");
        while (hasil.next()) {
            str = str + (hasil.getInt(1) + "\t" + hasil.getString(2)+ "\t" + hasil.getString(3)+ "\t" + hasil.getDate(4)+ "\t" + hasil.getString(5));
        }
        stat.close();
        koneksi.close();
    } catch (SQLException sqle) {
        str = "SQLException error";
    } catch (ClassNotFoundException cnfe) {
        str = "ClassNotFoundException error";
    }
    return str;
 }
}

And here's my web.xml file:

这是我的 web.xml 文件:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 version="2.5"> 
<servlet>
    <servlet-name>DirViewServlet</servlet-name>
    <servlet-class>DirectorsViewServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>DirViewServlet</servlet-name>
    <url-pattern>/directors-view</url-pattern>
</servlet-mapping>
</web-app>

The problem is, when I access it in my browser with this local URL http://www.myhost.com:8088/projectmovie/directors-view

问题是,当我使用本地 URL http://www.myhost.com:8088/projectmovie/directors-view在浏览器中访问它时

The result is "ClassNotFoundException error". How to solve it?

结果是“ClassNotFoundException 错误”。如何解决?

I read someone saying servlet and JDBC are somewhat orthogonal tecnology. Any further explanation of what is that mean? And why?

我读到有人说 servlet 和 JDBC 在某种程度上是正交的技术。任何进一步的解释是什么意思?为什么?

Thanks.

谢谢。

采纳答案by BalusC

A ClassNotFoundExceptionis a rather simple exception, unrelated to servlets/JDBC (look, it's from java.langpackage, indicating basic Java, not from javax.servletnor java.sqlpackage which would otherwise indicate Servlet or JDBC problem). It just means that the in the exception message mentioned class is missing in the runtime classpath.

AClassNotFoundException是一个相当简单的异常,与 servlets/JDBC 无关(看,它来自java.lang包,表示基本的 Java,而不是来自javax.servletjava.sql包,否则表示 Servlet 或 JDBC 问题)。这只是意味着异常消息中提到的类在运行时类路径中丢失。

Unfortunately, the in the exception message mentioned class is in your case nowhere printed/logged. The exception handling in the given code is terribly poor. The code is completely suppressing the exception and returning a custom message as if it's a result from the DB. The caller of that code couldn't even distinguish if the DB interaction has succeeded or not. If you rewrite the code in such way that it properly throwsthe exception, or at least prints its stack trace, then you should see the missing class in the exception message like so

不幸的是,在异常消息中提到的类在您的情况下无处打印/记录。给定代码中的异常处理非常糟糕。该代码完全抑制了异常并返回一条自定义消息,就好像它是来自数据库的结果一样。该代码的调用者甚至无法区分数据库交互是否成功。如果您以正确抛出异常的方式重写代码,或者至少打印其堆栈跟踪,那么您应该在异常消息中看到丢失的类,如下所示

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    at ....

This is in turn self-explaining: the JDBC driver class (or in this particular case, the JAR file containing the JDBC driver class) is missing in the runtime classpath.

这反过来又不言自明:运行时类路径中缺少 JDBC 驱动程序类(或在这种特殊情况下,包含 JDBC 驱动程序类的 JAR 文件)。

Just drop the JDBC driver JAR file in webapp's runtime classpath. The /WEB-INF/libfolder participates in the webapp's runtime classpath. Just drop the JAR file straight in there and rebuild/redeploy/restart.

只需将 JDBC 驱动程序 JAR 文件放到 webapp 的运行时类路径中。该/WEB-INF/lib文件夹参与 webapp 的运行时类路径。只需将 JAR 文件直接放在那里并重建/重新部署/重新启动。

See also:

也可以看看:



Unrelatedto the concrete problem, I recommend to carefully read this post for a proper kickoff example of JSP+Servlet+JDBC: Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern. Not only is the code poor in handling of exceptions, it's also poor in handling of DB resources. Those may leak away in case of exceptions.

具体问题无关,我建议您仔细阅读这篇文章,以获取JSP+Servlet+JDBC 的正确启动示例:使用 MVC 和 DAO 模式在 JSP 页面中的 HTML 中显示 JDBC ResultSet。代码不仅在处理异常方面很差,而且在处理数据库资源方面也很差。如果出现异常,这些可能会泄漏。

回答by Muhammad Usman

If you are getting Class not found for 'com.mysql.jdbc.Driver' class it means your project is missing jdbc drivers jar file. You need to download jdbc drivers based on your Database and place that .jar file in 'WebContent\WEB-INF\lib' in your project.

如果您发现 Class not found for 'com.mysql.jdbc.Driver' 类,则意味着您的项目缺少 jdbc 驱动程序 jar 文件。您需要根据您的数据库下载 jdbc 驱动程序,并将该 .jar 文件放在您的项目中的“WebContent\WEB-INF\lib”中。

If you are using MySQL then you can download drivers from here.

如果您使用 MySQL,那么您可以从这里下载驱动程序。

I hope this helps.

我希望这有帮助。