java 当我从外部类调用它时,为什么会得到 ClassNotFoundException?

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

Why do I get ClassNotFoundException when I call it from outside class?

javamysqltomcatservlets

提问by JavaDeveloper

Below is the code that works perfectly fine when it is executed from main (ie in eclipse RunAs java application). However if I call Statement getStatementfrom outside ( meaning a servlet calling it via a put ) in the same package I get java.lang.ClassNotFoundException: com.mysql.jdbc.Driver. Any pointers to why ?

下面是从 main (即在 eclipse RunAs java 应用程序中)执行时运行良好的代码。但是,如果我Statement getStatement在同一个包中从外部调用(意味着 servlet 通过 put 调用它),我会得到 java.lang.ClassNotFoundException: com.mysql.jdbc.Driver。任何指向为什么的指针?

public class DBConnectivity {

    private static Statement getStatement(String username, String password) throws SQLException, ClassNotFoundException {
        Properties prop = new Properties();
        prop.put("user", "root");
        prop.put("password", "password");

        Class.forName("com.mysql.jdbc.Driver");

        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/keeptrack", prop);
        Statement stmt = conn.createStatement();

        return stmt;
    }

    public void put(String username, String password, String table,
            String name, String exercise, String wsj, String food)
            throws SQLException, ClassNotFoundException {
        Statement stmt = getStatement(username, password);
        // checkIfTableExists(stmt, table);     
        stmt.executeUpdate(
                "insert into " + table +
                " " +
                "values(\'" + name + "\', \'" +  exercise + "\', \'" + wsj + "\', \'" + food + "\')");
    }   


    public List<String> get(String username, String password, String table)
            throws SQLException, ClassNotFoundException {
        Statement stmt = getStatement(username, password);
        //checkIfTableExists(stmt, table);      
        ResultSet rs = stmt.executeQuery("select FOOD from " + table);

        List<String> foodData = new ArrayList<String>();

        while(rs.next()) {
            String output = rs.getString("FOOD");
            foodData.add(output);
        //  System.out.println("wohoo: " + output);
        }

        return foodData;
    }   

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        DBConnectivity conn = new DBConnectivity();
        conn.put("root", "password", "trackTable", "D", "B", "C", "D");
        conn.get("root", "password", "trackTable");
    }
}

Here is the servlet which calls the database:

这是调用数据库的 servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("firstname");
        String password = request.getParameter("lastname");
        String firstname  = username;
        String exercise = request.getParameter("exerise");
        String wsj = request.getParameter("wsj");
        String food = request.getParameter("food");


        try {
            new DBConnectivity().put(username, password, "trackTable", firstname, exercise, wsj, food);
        } catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

The new DBConnectivity().putcall results in ClassNotFoundException.

new DBConnectivity().put调用导致ClassNotFoundException

Stack trace is :

堆栈跟踪是:

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1295)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1147)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at org.ameya.dynasty.DBConnectivity.getStatement(DBConnectivity.java:27)
at org.ameya.dynasty.DBConnectivity.get(DBConnectivity.java:63)
at org.ameya.dynasty.ServletIndex.doGet(ServletIndex.java:39)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:744)

回答by icza

Your error:

你的错误:

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

If it works running from Eclipse, that means you have the MySql jdbc dirver jar in the classpath of your project, but it is not available to your web application.

如果它可以从 Eclipse 运行,则意味着您的项目的类路径中有 MySql jdbc dirver jar,但它对您的 Web 应用程序不可用。

The project class path (build path) is not the same as the class path of your web application when deployed. Not all jars being on your project class path get exported automatically.

项目类路径(构建路径)与部署时 Web 应用程序的类路径不同。并非所有项目类路径上的 jar 都会自动导出。

Usually jars in the WEB-INF/libwill be available for the web application, but jars outside of that will not.

通常WEB-INF/lib,Web 应用程序可以使用 中的 jar,但外部的 jar 则不行。

You should either place the MySql jdbc driver jar in WEB-INF/lib, or add it to the lib folder of your Servlet container (Tomcat in your case judging by the exception stack trace).

您应该将 MySql jdbc 驱动程序 jar 放在 中WEB-INF/lib,或者将其添加到 Servlet 容器的 lib 文件夹中(根据异常堆栈跟踪判断,在您的情况下为 Tomcat)。

回答by Sush

You have to include mysql-connector-java-5.1.24-bin.jarlibrary file into your project. Then it will not give the error class not found. this file located inside C:\Program Files\MySQL\Connector J 5.1.20.0folder.

您必须将mysql-connector-java-5.1.24-bin.jar库文件包含到您的项目中。然后它不会给出未找到的错误类。此文件位于C:\Program Files\MySQL\Connector J 5.1.20.0文件夹内。

回答by Altmish-E-Azam

Add mysql-conneter jar in your project library. You can download it from below link

在您的项目库中添加 mysql-conneter jar。你可以从下面的链接下载

Download Connector Jar file

下载连接器 Jar 文件

回答by Ganesh Ghag

make sure that the packager you are using for creating war file (it could just as well be eclipse), is putting the mysql driver jar file in the war's web-inf lib.

确保您用于创建 war 文件的打包程序(它也可以是 eclipse),将 mysql 驱动程序 jar 文件放在 war 的 web-inf 库中。

typically, in eclipse you ensure above by going to project properties->deployment assembly and making sure your driver jar is included

通常,在 Eclipse 中,您通过转到项目属性-> 部署程序集并确保包含驱动程序 jar 来确保上述内容

回答by Sergio Gutiérrez Jiménez

If you execute the same method (main) in other class inside the project, must be executed perfectly.

如果main在项目内部的其他类中执行相同的方法( ),一定要完美执行。

The classloader is the same, but you can't access to the method getStatementoutside the class DBConnectivitybecause the method is private.

类加载器是一样的,但是你不能访问getStatement类外的方法,DBConnectivity因为该方法是私有的。

You could execute this method by reflection.

您可以通过反射来执行此方法。