免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
Tomcat ClassLoader研究
Tomcat的ClassLoader層次結(jié)構(gòu):
Bootstrap
| System
|
Common
/ Catalina Shared
/ \
Webapp1 Webapp2 ...
源代碼如下:
org.apache.catalina.startup.Bootstrap類(tomcat主類)
view plaincopy to clipboardprint?
public final class Bootstrap {
// ------------------------------------------------------- Static Variables
/**
* Debugging detail level for processing the startup.
*/
private static int debug = 0;
// ----------------------------------------------------------- Main Program
/**
* The main program for the bootstrap.
*
* @param args Command line arguments to be processed
*/
public static void main(String args[]) {
// Set the debug flag appropriately
for (int i = 0; i < args.length; i++)  {
if ("-debug".equals(args[i]))
debug = 1;
}
// Configure catalina.base from catalina.home if not yet set
if (System.getProperty("catalina.base") == null)
System.setProperty("catalina.base", getCatalinaHome());
// Construct the class loaders we will need
ClassLoader commonLoader = null;
ClassLoader catalinaLoader = null;
ClassLoader sharedLoader = null;
try {
File unpacked[] = new File[1];
File packed[] = new File[1];
File packed2[] = new File[2];
ClassLoaderFactory.setDebug(debug);
unpacked[0] = new File(getCatalinaHome(),
"common" + File.separator + "classes");
packed2[0] = new File(getCatalinaHome(),
"common" + File.separator + "endorsed");
packed2[1] = new File(getCatalinaHome(),
"common" + File.separator + "lib");
commonLoader =
ClassLoaderFactory.createClassLoader(unpacked, packed2, null);
unpacked[0] = new File(getCatalinaHome(),
"server" + File.separator + "classes");
packed[0] = new File(getCatalinaHome(),
"server" + File.separator + "lib");
catalinaLoader =
ClassLoaderFactory.createClassLoader(unpacked, packed,
commonLoader);
unpacked[0] = new File(getCatalinaBase(),
"shared" + File.separator + "classes");
packed[0] = new File(getCatalinaBase(),
"shared" + File.separator + "lib");
sharedLoader =
ClassLoaderFactory.createClassLoader(unpacked, packed,
commonLoader);
} catch (Throwable t) {
log("Class loader creation threw exception", t);
System.exit(1);
}
Thread.currentThread().setContextClassLoader(catalinaLoader);
// Load our startup class and call its process() method
try {
SecurityClassLoad.securityClassLoad(catalinaLoader);
// Instantiate a startup class instance
if (debug >= 1)
log("Loading startup class");
Class startupClass =
catalinaLoader.loadClass
("org.apache.catalina.startup.Catalina");
Object startupInstance = startupClass.newInstance();
// Set the shared extensions class loader
if (debug >= 1)
log("Setting startup class properties");
String methodName = "setParentClassLoader";
Class paramTypes[] = new Class[1];
paramTypes[0] = Class.forName("java.lang.ClassLoader");
Object paramValues[] = new Object[1];
paramValues[0] = sharedLoader;
Method method =
startupInstance.getClass().getMethod(methodName, paramTypes);
method.invoke(startupInstance, paramValues);
// Call the process() method
if (debug >= 1)
log("Calling startup class process() method");
methodName = "process";
paramTypes = new Class[1];
paramTypes[0] = args.getClass();
paramValues = new Object[1];
paramValues[0] = args;
method =
startupInstance.getClass().getMethod(methodName, paramTypes);
method.invoke(startupInstance, paramValues);
} catch (Exception e) {
System.out.println("Exception during startup processing");
e.printStackTrace(System.out);
System.exit(2);
}
}
 
其中:
commonLoader =
ClassLoaderFactory.createClassLoader(unpacked, packed2, null);
創(chuàng)建common classloader,以AppClassLoader為父ClassLoader
catalinaLoader =
ClassLoaderFactory.createClassLoader(unpacked, packed,
commonLoader);
創(chuàng)建catalina classloader,以common classloader為父classloader
sharedLoader =
ClassLoaderFactory.createClassLoader(unpacked, packed,
commonLoader);
創(chuàng)建share classloader,以common classloader為父classloader
Thread.currentThread().setContextClassLoader(catalinaLoader);
設(shè)置ContextClassLoader為catalina classloader
org.apache.catalina.startup.ClassLoaderFactory類
view plaincopy to clipboardprint?
public static ClassLoader createClassLoader(File unpacked[],
File packed[],
ClassLoader parent)
throws Exception {
if (debug >= 1)
log("Creating new class loader");
// Construct the "class path" for this class loader
ArrayList list = new ArrayList();
// Add unpacked directories
if (unpacked != null) {
for (int i = 0; i < unpacked.length; i++)  {
File file = unpacked[i];
if (!file.isDirectory() || !file.exists() || !file.canRead())
continue;
if (debug >= 1)
log("  Including directory " + file.getAbsolutePath());
URL url = new URL("file", null,
file.getCanonicalPath() + File.separator);
list.add(url.toString());
}
}
// Add packed directory JAR files
if (packed != null) {
for (int i = 0; i < packed.length; i++) {
File directory = packed[i];
if (!directory.isDirectory() || !directory.exists() ||
!directory.canRead())
continue;
String filenames[] = directory.list();
for (int j = 0; j < filenames.length; j++) {
String filename = filenames[j].toLowerCase();
if (!filename.endsWith(".jar"))
continue;
File file = new File(directory, filenames[j]);
if (debug >= 1)
log("  Including jar file " + file.getAbsolutePath());
URL url = new URL("file", null,
file.getCanonicalPath());
list.add(url.toString());
}
}
}
// Construct the class loader itself
String array[] = (String[]) list.toArray(new String[list.size()]);
StandardClassLoader classLoader = null;
if (parent == null)
classLoader = new StandardClassLoader(array);
else
classLoader = new StandardClassLoader(array, parent);
classLoader.setDelegate(true);
return (classLoader);
}
 
ClassLoaderFactory創(chuàng)建的是StandardClassLoader(org.apache.catalina.loader包中)
由Bootstrap類調(diào)用Catalina類的process()方法,再調(diào)用execute()方法,再調(diào)用start()來啟動Server實例。
當Tomcat開啟每個Context時,是調(diào)用的StandardContext的start()方法,其中:
設(shè)置Loader為WebappLoader
view plaincopy to clipboardprint?
if (getLoader() == null) {      // (2) Required by Manager
if (getPrivileged()) {
if (debug >= 1)
log("Configuring privileged default Loader");
setLoader(new WebappLoader(this.getClass().getClassLoader()));
} else {
if (debug >= 1)
log("Configuring non-privileged default Loader");
setLoader(new WebappLoader(getParentClassLoader()));
}
}
 
然后調(diào)用:bindThread(),設(shè)置當前線程的ClassLoader為WebappLoader的ClassLoader,即為WebappClassLoader
view plaincopy to clipboardprint?
private ClassLoader bindThread() {
ClassLoader oldContextClassLoader =
Thread.currentThread().getContextClassLoader();
if (getResources() == null)
return oldContextClassLoader;
Thread.currentThread().setContextClassLoader
(getLoader().getClassLoader());
DirContextURLStreamHandler.bind(getResources());
if (isUseNaming()) {
try {
ContextBindings.bindThread(this, this);
} catch (NamingException e) {
// Silent catch, as this is a normal case during the early
// startup stages
}
}
return oldContextClassLoader;
}
 
WebappLoader的ClassLoader的賦值如下:
view plaincopy to clipboardprint?
private String loaderClass =
"org.apache.catalina.loader.WebappClassLoader";
......
public void start() throws LifecycleException {
// Validate and update our current component state
if (started)
throw new LifecycleException
(sm.getString("webappLoader.alreadyStarted"));
if (debug >= 1)
log(sm.getString("webappLoader.starting"));
lifecycle.fireLifecycleEvent(START_EVENT, null);
started = true;
if (container.getResources() == null)
return;
// Register a stream handler factory for the JNDI protocol
URLStreamHandlerFactory streamHandlerFactory =
new DirContextURLStreamHandlerFactory();
try {
URL.setURLStreamHandlerFactory(streamHandlerFactory);
} catch (Throwable t) {
// Ignore the error here.
}
// Construct a class loader based on our current repositories list
try {
classLoader = createClassLoader();
classLoader.setResources(container.getResources());
classLoader.setDebug(this.debug);
classLoader.setDelegate(this.delegate);
if (container instanceof StandardContext)
classLoader.setAntiJARLocking(((StandardContext) container).getAntiJARLocking());
for (int i = 0; i < repositories.length; i++) {
classLoader.addRepository(repositories[i]);
}
// Configure our repositories
setRepositories();
setClassPath();
setPermissions();
if (classLoader instanceof Lifecycle)
((Lifecycle) classLoader).start();
// Binding the Webapp class loader to the directory context
DirContextURLStreamHandler.bind
((ClassLoader) classLoader, this.container.getResources());
} catch (Throwable t) {
throw new LifecycleException("start: ", t);
}
// Validate that all required packages are actually available
validatePackages();
// Start our background thread if we are reloadable
if (reloadable) {
log(sm.getString("webappLoader.reloading"));
try {
threadStart();
} catch (IllegalStateException e) {
throw new LifecycleException(e);
}
}
}
......
private WebappClassLoader createClassLoader()
throws Exception {
Class clazz = Class.forName(loaderClass);
WebappClassLoader classLoader = null;
if (parentClassLoader == null) {
// Will cause a ClassCast is the class does not extend WCL, but
// this is on purpose (the exception will be caught and rethrown)
classLoader = (WebappClassLoader) clazz.newInstance();
} else {
Class[] argTypes = { ClassLoader.class };
Object[] args = { parentClassLoader };
Constructor constr = clazz.getConstructor(argTypes);
classLoader = (WebappClassLoader) constr.newInstance(args);
}
return classLoader;
}
 
在WebappClassLoader中,其findClass的搜索順序與一般的ClassLoader的搜索順序不同。
一般的ClassLoader的搜索順序為:
將其委托給父ClassLoader,如果父ClassLoader不能載入相應(yīng)類,則才交給自己處理
但是WebappClassLoader中,其是先由自己來處理,如果不行再委托給父ClassLoader
相關(guān)源代碼如下:
view plaincopy to clipboardprint?
Class clazz = null;
try {
if (debug >= 4)
log("      findClassInternal(" + name + ")");
try {
clazz = findClassInternal(name);
} catch(ClassNotFoundException cnfe) {
if (!hasExternalRepositories) {
throw cnfe;
}
} catch(AccessControlException ace) {
ace.printStackTrace();
throw new ClassNotFoundException(name);
} catch (RuntimeException e) {
if (debug >= 4)
log("      -->RuntimeException Rethrown", e);
throw e;
}
if ((clazz == null) && hasExternalRepositories) {
try {
clazz = super.findClass(name);
} catch(AccessControlException ace) {
throw new ClassNotFoundException(name);
} catch (RuntimeException e) {
if (debug >= 4)
log("      -->RuntimeException Rethrown", e);
throw e;
}
}
if (clazz == null) {
if (debug >= 3)
log("    --> Returning ClassNotFoundException");
throw new ClassNotFoundException(name);
}
} catch (ClassNotFoundException e) {
if (debug >= 3)
log("    --> Passing on ClassNotFoundException", e);
throw e;
}
 
以下引自tomcat的說明文檔,說明了加載類的順序
Therefore, from the perspective of a web application, class or resource loading looks in the following repositories, in this order:
/WEB-INF/classes of your web application
/WEB-INF/lib/*.jar of your web application
Bootstrap classes of your JVM
System class loader classses (described above)
$CATALINA_HOME/common/classes
$CATALINA_HOME/common/endorsed/*.jar
$CATALINA_HOME/common/lib/*.jar
$CATALINA_BASE/shared/classes
$CATALINA_BASE/shared/lib/*.jar
Class Loader HOW-TO
Overview
Class Loader Definitions
XML Parsers and JSE 5
Running under a security manager
Like many server applications, Tomcat 6 installs a variety of class loaders (that is, classes that implement java.lang.ClassLoader) to allow different portions of the container, and the web applications running on the container, to have access to different repositories of available classes and resources. This mechanism is used to provide the functionality defined in the Servlet Specification, version 2.4 -- in particular, Sections 9.4 and 9.6.
In a J2SE 2 (that is, J2SE 1.2 or later) environment, class loaders are arranged in a parent-child tree. Normally, when a class loader is asked to load a particular class or resource, it delegates the request to a parent class loader first, and then looks in its own repositories only if the parent class loader(s) cannot find the requested class or resource. The model for web application class loaders differs slightly from this, as discussed below, but the main principles are the same.
When Tomcat 6 is started, it creates a set of class loaders that are organized into the following parent-child relationships, where the parent class loader is above the child class loader:
Bootstrap | System | Common / Webapp1 Webapp2 ...
The characteristics of each of these class loaders, including the source of classes and resources that they make visible, are discussed in detail in the following section.
As indicated in the diagram above, Tomcat 6 creates the following class loaders as it is initialized:
Bootstrap - This class loader contains the basic runtime classes provided by the Java Virtual Machine, plus any classes from JAR files present in the System Extensions directory ($JAVA_HOME/jre/lib/ext). NOTE - Some JVMs may implement this as more than one class loader, or it may not be visible (as a class loader) at all.
System - This class loader is normally initialized from the contents of the CLASSPATH environment variable. All such classes are visible to both Tomcat internal classes, and to web applications. However, the standard Tomcat 6 startup scripts ($CATALINA_HOME/bin/catalina.sh or%CATALINA_HOME%\bin\catalina.bat) totally ignore the contents of the CLASSPATH environment variable itself, and instead build the System class loader from the following repositories: $CATALINA_HOME/bin/bootstrap.jar - Contains the main() method that is used to initialize the Tomcat 6 server, and the class loader implementation classes it depends on.
$CATALINA_HOME/bin/tomcat-juli.jar - Package renamed Commons logging API, and java.util.logging LogManager.
Common - This class loader contains additional classes that are made visible to both Tomcat internal classes and to all web applications. Normally, application classes should NOT be placed here. All unpacked classes and resources in $CATALINA_HOME/lib, as well as classes and resources in JAR files are made visible through this class loader. By default, that includes the following: annotations-api.jar - JEE annotations classes.
catalina.jar - Implementation of the Catalina servlet container portion of Tomcat 6.
catalina-ant.jar - Tomcat Catalina Ant tasks.
catalina-ha.jar - High availability package.
catalina-tribes.jar - Group communication package.
el-api.jar - EL 2.1 API.
jasper.jar - Jasper 2 Compiler and Runtime.
jasper-el.jar - Jasper 2 EL implementation.
jasper-jdt.jar - Eclipse JDT 3.2 Java compiler.
jsp-api.jar - JSP 2.1 API.
servlet-api.jar - Servlet 2.5 API.
tomcat-coyote.jar - Tomcat connectors and utility classes.
tomcat-dbcp.jar - package renamed database connection pool based on Commons DBCP.
tomcat-i18n-**.jar - Optional JARs containing resource bundles for other languages. As default bundles are also included in each individual JAR, they can be safely removed if no internationalization of messages is needed.
WebappX - A class loader is created for each web application that is deployed in a single Tomcat 6 instance. All unpacked classes and resources in the/WEB-INF/classes directory of your web application archive, plus classes and resources in JAR files under the /WEB-INF/lib directory of your web application archive, are made visible to the containing web application, but to no others.
As mentioned above, the web application class loader diverges from the default Java 2 delegation model (in accordance with the recommendations in the Servlet Specification, version 2.3, section 9.7.2 Web Application Classloader). When a request to load a class from the web application's WebappX class loader is processed, this class loader will look in the local repositories first, instead of delegating before looking. There are exceptions. Classes which are part of the JRE base classes cannot be overriden. For some classes (such as the XML parser components in J2SE 1.4+), the J2SE 1.4 endorsed feature can be used. Last, any JAR containing servlet API classes will be ignored by the classloader. All other class loaders in Tomcat 6 follow the usual delegation pattern.
Therefore, from the perspective of a web application, class or resource loading looks in the following repositories, in this order:
Bootstrap classes of your JVM
System class loader classes (described above)
/WEB-INF/classes of your web application
/WEB-INF/lib/*.jar of your web application
$CATALINA_HOME/lib
$CATALINA_HOME/lib/*.jar
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
談?wù)?Java 類加載機制
Tomcat 6.0 Class Loader
淺議tomcat與classloader
JAVA讀取文件的兩種方法:JAVA.IO和JAVA.LANG.CLASSLOADER
Tomcat研究之ClassLoader
spring boot啟動分析
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服