我使用 Java 开发了一个 Web 应用程序。当我将它部署到我的应用程序服务器(Jetty、Tomcat、JBoss、GlassFish 等)时会引发错误。我可以在堆栈跟踪中看到此错误消息:
java.lang.ClassNotFoundException
Run Code Online (Sandbox Code Playgroud)
或者
java.lang.NoClassDefFoundError
Run Code Online (Sandbox Code Playgroud)
这是什么意思,我该如何解决?
这是什么意思?
首先,让我们看看 的含义java.lang.ClassNotFoundException:
当应用程序尝试通过其字符串名称加载类时抛出:
forName类中的方法Class。findSystemClass类中的方法ClassLoader。loadClass类中的方法ClassLoader。但是找不到具有指定名称的类的定义。
通常,当尝试以这种形式手动打开连接时会发生这种情况:
String jdbcDriver = "...'; //name of your driver
Class.forName(jdbcDriver);
Run Code Online (Sandbox Code Playgroud)
或者当您引用属于外部库的类时,奇怪的是当应用程序服务器尝试部署应用程序时无法加载该类。
让我们看看java.lang.NoClassDefFoundError(强调我的)的含义:
如果 Java 虚拟机或
ClassLoader实例尝试在类的定义中加载(作为正常方法调用的一部分或作为使用 new 表达式创建新实例的一部分)并且找不到类的定义,则抛出。编译当前正在执行的类时,搜索到的类定义存在,但无法再找到该定义。
最后一部分说明了一切:该类在编译时即存在,即当我通过 IDE 编译应用程序时,但在运行时即部署应用程序时不可用。
我该如何解决?
在 Java Web 应用程序中,您的应用程序使用的所有第三方库都必须放在 WEB-INF/lib 文件夹中。确保所有必需的库(jar)都放在那里。您可以轻松检查:
- <webapp folder>
- WEB-INF
- lib
+ jar1
+ jar2
+ ...
- META-INF
- <rest of your folders>
Run Code Online (Sandbox Code Playgroud)
此问题通常出现在 JDBC 连接 jar(MySQL、Derby、MSSQL、Oracle 等)或 Web MVC 框架库(如 JSF 或 Spring MVC)中。
考虑到某些第三方库依赖于其他第三方库,因此您必须将它们全部添加到 WEB-INF/lib 中才能使应用程序正常工作。RichFaces 4 库就是一个很好的例子,您必须手动下载和添加外部库。
Note for Maven users: you should not experience these problems unless you have set the libraries as provided, test or system. If set to provided, you're responsible to add the libraries somewhere in the classpath. You can find more info about the dependency scopes here: Introduction to the Dependency Mechanism
In case the library must be shared among several applications that will be deployed on your application server e.g. MySQL connector for two applications, there's another alternative. Instead of deploying two war files each with their own MySQL connector library, place this library in the common library folder of the server application, this will enable the library to be in the classpath of all the deployed applications.
This folder vary from application server.
<tomcat_home>/lib<jboss_home>/standalone/lib| 归档时间: |
|
| 查看次数: |
9874 次 |
| 最近记录: |