简体   繁体   中英

Getting ClassNotFoundException: oracle.jdbc.driver.OracleDriver in one but not in another class

On executing below code:

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

I'm getting exception:

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

I've already imported all tomcat jars & ojdbc14.jar.

Weird thing is when I write same code in a separate class in main(), it works:

public static void main(String[] args) {
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        System.out.println("works");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

Looks like you did not place the ojdbc14.jar at right location. It should reside in Web-INF/lib folder where your other project specific jar lies. For debugging purpose try to import the class and see below statement is interpreted correctly

OracleDriver od=   new OracleDriver();

There might several options

Options :

  1. Make sure to put ojdbcxx.jar file under WEB-INF/lib directory.
  2. Put ojdbcxx.jar under <tomcat home dir>/common/lib .

You need to understand calling mechanism of main() and doPost.

main()

The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.

build path for this is where you have your Java code, so lib should be present here.

doPost()

It is invoked by Server.

Structure of it is

          App Name  
              -WEB-INF
                   -classes (all class file)
                   -lib (all jars) 
              -META-INF

So here, jar you need to place is in lib folder.

I guess servlet is set to early initialization. put ojdbc14.jar in tomcat lib directory or set servlet to lazy initialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM