java - ClassNotFoundException 当通过 java 的 Servlets 运行 JDBC 时

标签 java mysql eclipse servlets jdbc

我在尝试创建 MysqlDataSource 对象时遇到了这个奇怪的异常(或者至少我认为这是问题的根源)。

让我先准确描述一下我目前所拥有的:
我使用 Tomcat7 作为容器,使用 Eclipse 作为 IDE,以创建一个 JSP 登录表单,它接受用户名和密码,然后调用一个名为“LoginController”的 Servlet。每当您单击“登录”按钮时,LoginController 都会根据 MySql 数据库验证输入(用户名和密码)。
好吧,至少这是计划……

一切似乎都很好,直到它到达需要实例化 com.mysql.jdbc.jdbc2.optional.MysqlDataSource 对象的部分。
我收到这个讨厌的错误:

HTTP Status 500 - Servlet execution threw an exception

type Exception report

message Servlet execution threw an exception

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Servlet execution threw an exception
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

java.lang.NoClassDefFoundError: com/mysql/jdbc/jdbc2/optional/MysqlDataSource
    model.Authenticator.authenticateLogin(Authenticator.java:13)
    controller.LoginController.doPost(LoginController.java:52)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

java.lang.ClassNotFoundException: com.mysql.jdbc.jdbc2.optional.MysqlDataSource
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
    model.Authenticator.authenticateLogin(Authenticator.java:13)
    controller.LoginController.doPost(LoginController.java:52)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

note The full stack trace of the root cause is available in the Apache Tomcat/7.0.55 logs.

现在,我了解到服务器“找不到 MysqlDataSource”,我只是不明白为什么,因为我DID 通过“项目属性”将所需的 jar 文件添加到项目中->Java Build Path->Libraries->Add External Jar...”,在Project Explorer中也可以看到:

enter image description here

更令人惊讶的是,当我打开一个常规的 Java 应用程序项目(而不是动态 Web 项目)时,我能够毫无问题地连接到 Mysql 数据库并运行查询。
只是在 Tomcat 上它不起作用......

我在网上看了一圈,看到有人建议通过“Java Source Attachment”来“Attach the source ...”,但不知道该怎么做...

如有任何帮助,我们将不胜感激!

最佳答案

当您将文件作为外部 jar 添加到依赖项中时,它不会在构建应用程序时包含在 war 文件中。需要将jar复制到项目中的WEB-INF/lib目录下或者放到Tomcat的lib目录下

关于java - ClassNotFoundException 当通过 java 的 Servlets 运行 JDBC 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25168254/

相关文章:

java - Spring MVC 基于 Java 的配置看不到类路径属性文件

python - SQLAlchemy 复杂查询

php - 只有一个文件数据进入数据库

java - 根据 Eclipse 插件中 View 的可见性使菜单条目可见?

android - 用于 XML 文件的 Eclipse 拾色器插件

eclipse - 在Eclipse中编辑代码时如何禁用粗体字体?

java - 有什么方法可以覆盖 Java 应用程序中的库类

java - 了解 JIRA 依赖项和包导入

java - 为什么 iText 不将靠近页面底部的表格添加到文档中?

mysql - 这个MYSQL可以优化吗?