1

I have a very simple line of code that is called from an .xhtml file ( in a JSF 2.0 project ) which looks like:

try {
    Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e) {
    e.printStackTrace();
}

So in my C:\ folder I have the file: mysql-connector-java-5.1.24-bin. I have added this jar as an extenral jar in IntelliJ Idea 12.

When I start my application like this, I get the "Class not found exception." However, when I add this dependency to my pom.xml file:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

I get no exception and class is loaded fine.

Here is a screenshot: enter image description here

The jar file I underlined with green is the Jar added externally from **File -> Project Structure -> Libraries **

The one I underlined with red is the jar file that is downloaded by maven.

My question is: Why do I get the Class not found exception, although I have added the Jar externally?

In case I require a Jar file that I will not be able to download via maven, what am I supposed to do?

One extra information: I created a sample Java project with one class only, and I added this external Jar file with the method I explained above. No maven, no tomcat, nothing. Just a simple main method. I ran this same code, and it worked fine. So it has to have something to do with IntelliJ and one or more of:

  • Maven
  • Tomcat ( Deploying a War file )
  • Maven and Tomcat?

Edit: When I add the external Jar only and try importing a class from com.mysql.jdbc... IntelliJ IDEA does not come up with any warnings / errors. It finds the class, however after the deployment, it seems like the Class can not be found anymore.

4

1 回答 1

4

webapp 在tomcat 上部署并运行。Tomcat 不关心 IntelliJ 源项目中的 jar。对 tomcat 重要的是部署的 webapp 的 WEB-INF/lib 目录下的一组 jar 文件。只有那些 jars 在 webapp 的类路径中。

我不太清楚 IntelliJ 如何构建和部署 webapps,尤其是当 Maven 出现在图片中时。但我猜它只部署 Maven 项目的编译和运行时范围内的 jar。对于外部 jar,可能可以配置 IntelliJ 项目,以便将其包含在构建和部署的存档中。

但无论如何,如果你使用 Maven,你必须能够在不使用 IntelliJ 的情况下构建你的战争。这就是构建工具的全部意义所在:它用于在没有 IDE 的情况下构建项目。所以Maven必须知道所有必要的jar。因此,如果 Maven 中心不提供该 jar,则应将其添加到您自己的本地 Maven 存储库(至少)或您公司的私有存储库中。

于 2013-04-19T21:41:53.567 回答