Search code examples
javamavenintellij-ideaclassnotfoundexception

NoCLassDefFoundError and ClassNotFoundException thrown when running TomCat in Intellij


I'm trying to build a server to host an slack bot on. I have included the external library org.json in the maven file and ran it and I don't get any errors in Intellij, but when I start to run it (with Tomcat Server 9.0.24) and send a POST to the server, I get both java.lang.NoClassDefFoundError: org/json/JSONObject and java.lang.ClassNotFoundException: org.json.JSONObject.

The solution seemed to be to include the actual .jar file in the compiling, but I think it already is as can be seen in Project Settings -> Libraries Libraries

The pom.xml includes the dependencies.

<dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.json/json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20190722</version>
        </dependency>
    </dependencies>

The code that triggers the error.

// Convert POST body to json
        JSONObject json = new JSONObject(jb.toString());

        // Print out the contents of challenge
        System.out.println(json.get("challenge"));

It's also only org.json that triggers the error, not the other dependency javax.servlet

I have seen some solutions to this, but most of them are for Eclipse or outdated Intellij. I have also tried copying the .jar files of the libraries straight to WEB-INF/lib but that didn't work either


Solution

  • I solved it by adding the .jar file for the library to the WEB-INF/lib folder and running mvn clean