Tomcat's CLASSPATH is different than Java's, and it does not include "." How do I change it?

classpath, java, noclassdeffounderror, tomcat

Solution

Classes required in a web application should be located within the web application in the WEB-INF/classes folder or packed in JAR files located in WEB-INF/lib. You should normally not use the servlet containers generic classpath settings for this, as you seem to attempt.

Problem

I've been spending hours trying to figure out why I've been getting the `java.lang.NoClassDefFoundError`, and I've narrowed down the cause to Tomcat's classpath. I used the code below to see what the path variables hold: ``` out.println("Classpath: '" + System.getProperty( "java.class.path" ) + "'" ); out.println("Ext dirs: '" + System.getProperty( "java.ext.dirs" ) + "'" ); out.println("Library path: '" + System.getProperty( "java.library.path" ) + "'" ); out.println("Path separator: '" + System.getProperty( "path.separator" ) + "'" ); ``` And the output is: ``` Classpath: ':/usr/local/tomcat/bin/bootstrap.jar' Ext dirs: '/usr/lib/jvm/java-6-sun-1.6.0.16/jre/lib/ext:/usr/java/packages/lib/ext' Library path: '/usr/lib/jvm/java-6-sun-1.6.0.16/jre/lib/i386/server:/usr/lib/jvm/java-6-sun-1.6.0.16/jre/lib/i386:/usr/lib/jvm/java-6-sun-1.6.0.16/jre/../lib/i386:/usr/java/packages/lib/i386:/lib:/usr/lib' Path separator: ':' ``` As you can see, Classpath does NOT start with "." as it's supposed to, and I believe that's why my program can't find the classes that I import from subdirectories in my webapp. To see where the classpath is set, i did `grep -R bootstrap.jar /usr/local/tomcat/`, and came accross this: `CLASSPATH="$CLASSPATH":"$CATALINA_HOME"/bin/bootstrap.jar` (in file `/usr/local/tomcat/bin/catalina.sh`) This makes me believe that for some reason $CLASSPATH is empty here. However, `echo $CLASSPATH` successfully returns `.:/usr/lib/jvm/java-6-sun/bin:/usr/local/tomcat/lib/servlet-api.jar` Can anybody help pin down the problem here? EDIT: All my servlet files are in `WEB-INF/classes/controllers/`, and the libraries i'm trying to load are class files in subdirectories. For example, if `ClassName.class` is in the WEB-INF/classes/controllers/packagename/ directory, I add `package packagename` to the start of `ClassName.java`, and I import it using `import packagename.*` in `someServlet.java`. EDIT2: I have solved my problem. My main issue was that, as written below, not using the correct package names. Also, I was trying to compile from inside the `classes/controllers/` directory, instead of compiling from `classes/`. Thank you all for your help!

Original source