Tomcat中的类加载策略和JDK中的委托模型略有不同。Tomcat Server在启动的时候将构造一个ClassLoader树,以保证模块的类库是私有的,ClassLoader结构如下:
Bootstrap
|
System
|
Common
/ \
Catalina Shared
/ ... ... \
webapp1 webappN
web应用的加载器(WebappX)和JDK的委托模型略有不同,这是根据Servlet2.3规范做出的。当WebappX被请求加载一个类 时,它首先尝试自己加载,而不是先委托给它的父加载器加载,如果无法加载该类,则委托它的父加载器加载。但是,对于下面的类,仍然要先委托给父加载器:
Classes which are part of the JRE base classes cannot be overriden. For some classes (such as the XML parser components in JDK 1.4+), the JDK 1.4 endorsed feature can be used (see the common classloader definition above). In addition, for the following class patterns, the classloader will always delegate first (and load the class itself if no parent classloader loads it):
javax.*
org.xml.sax.*
org.w3c.dom.*
org.apache.xerces.*
org.apache.xalan.*
Last, any JAR containing servlet API classes will be ignored by the classloader.
Tomcat中其他的加载器都是遵循委托模型的。
最后,以web应用的角度,要加载类或者资源时,会以下面的顺序查找:
Bootstrap classes of your JVM
System class loader classses (described above)
/WEB-INF/classes of your web application
/WEB-INF/lib/*.jar of your web application
$CATALINA_HOME/common/classes
$CATALINA_HOME/common/endorsed/*.jar
$CATALINA_HOME/common/lib/*.jar
$CATALINA_BASE/shared/classes
$CATALINA_BASE/shared/lib/*.jar
结论
对于只用于某一个web应用的类或资源,放在这个web应用下的/WEB-INF/classes目录下,如果是JAR,就放在这个web应用下的WEB-INF/lib目录下。
对于让所有的web应用共享的类或资源,放在$CATALINA_BASE/shared/classes目录下,如果是JAR,就放在$CATALINA_BASE/shared/lib目录下。