java - 我的 Java Web 应用程序中的 ClassNotFoundException/NoClassDefFoundError

标签 java jar java-war

我使用 Java 开发了一个 Web 应用程序。当我将其部署到我的应用程序服务器(Jetty、Tomcat、JBoss、GlassFish 等)时,会抛出错误。我可以在堆栈跟踪中看到此错误消息:

java.lang.ClassNotFoundException

或者

java.lang.NoClassDefFoundError

这是什么意思以及如何解决它?

最佳答案

What does this mean?

首先我们来看看 java.lang.ClassNotFoundException 的含义:

Thrown when an application tries to load in a class through its string name using:

  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader.
  • The loadClass method in class ClassLoader.

but no definition for the class with the specified name could be found.

通常,当尝试以这种形式手动打开连接时会发生这种情况:

String jdbcDriver = "...'; //name of your driver
Class.forName(jdbcDriver);

或者当您引用属于外部库的类时,奇怪当应用程序服务器尝试部署应用程序时无法加载该类。

让我们看看 java.lang.NoClassDefFoundError 的含义(强调我的):

Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

最后一部分说明了一切:该类在编译时存在,即当我通过 IDE 编译应用程序时,但它在运行时(即部署应用程序时)不可用。


how can I fix it?

在 Java Web 应用程序中,应用程序使用的所有第三方库都必须位于 WEB-INF/lib 文件夹中。确保所有必需的库(jar)都放置在那里。您可以轻松检查:

- <webapp folder>
  - WEB-INF
    - lib
      + jar1
      + jar2
      + ...
  - META-INF
  - <rest of your folders>

此问题通常出现在 JDBC 连接 jar(MySQL、Derby、MSSQL、Oracle 等)或 Web MVC 框架库(如 JSF 或 Spring MVC)中。

考虑到某些第三方库依赖其他第三方库,因此您必须将所有添加到WEB-INF/lib中才能使应用工作。 RichFaces 4 库就是一个很好的例子,where you have to download and add the external libraries manually .


注意Maven用户:除非您将库设置为provided,否则您不应该遇到这些问题, testsystem 。如果设置为provided ,您负责将库添加到类路径中的某个位置。您可以在此处找到有关依赖范围的更多信息:Introduction to the Dependency Mechanism


如果库必须在将部署在应用程序服务器上的多个应用程序之间共享,例如对于两个应用程序的 MySQL 连接器,还有另一种选择。不要部署两个 war 文件,每个文件都有自己的 MySQL 连接器库,而是将该库放置在服务器应用程序的公共(public)库文件夹中,这将使该库位于所有已部署应用程序的类路径中。

此文件夹因应用程序服务器而异。

  • Tomcat 7/8:<tomcat_home>/lib
  • JBoss 7/Wildfly:<jboss_home>/独立/lib

关于java - 我的 Java Web 应用程序中的 ClassNotFoundException/NoClassDefFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23905333/

相关文章:

java - 如何调用Akka helloworld?

java - 基于数据库的内容管理系统设计

java - Tomcat war run 应用程序 - 无法启动组件

java - 长查询列表中的模糊匹配API

maven - 如何在另一个项目中向Spring Boot Jar添加依赖项?

java - 无法在 Android Studio 中查看所有 .jar 代码

java - 获取 jar 内文件夹内的检索文件

java - 如何在 Spring Boot jboss/wildfly 中设置上下文路径?

java - 无法使用 IBM Rational Application Developer 将 WAR 文件部署到 Websphere

java - 扩展注释的接口(interface)