The eighth chapter loading device

Source: Internet
Author: User
I. Overview

The loader in this chapter differs from the simple loader of the first few sheets. Reasons are
①servlet should only allow classes to be loaded into the Web-inf/lib directory and its subdirectories. Security
The ② provides automatic reload functionality. That is, when the Web-inf/lib directory, or the class under the Web-inf/classes directory, changes, the Web application will reload the classes. This requires the loader to continually check the Servlet class using an additional thread.

This chapter has two terms:
① Warehouse (repository): Used to indicate where the class loader will search for classes to be loaded.
② Resource (Resource): Refers to a DirContext object in a class loader whose file root path refers to the file root path of the context. second, loader interface

The loader interface must be implemented for the loader in Tomcat.
There are a few rules to follow when loading servlets and related classes. For example, Servelt in an application can only reference classes that are deployed under the Web-inf/classes directory and its subdirectories, and can only access libraries in the Web-inf/lib directory.
What we said in Tomcat is that the Web application loader, not just the class loader, is the loading device. (There is a class loader in the loader!!!)
The loader should implement the Org.apache.catalina.Loader interface, and the class loader defaults to WebappClassLoader.

Package Org.apache.catalina;  

Import Java.beans.PropertyChangeListener;  
    Public interface Loader {public ClassLoader getclassloader ();              Public Container GetContainer ();  
    The loader is typically associated with a context-level container with public void Setcontainer (Container Container);  
    Public Defaultcontext getdefaultcontext ();  
    public void Setdefaultcontext (Defaultcontext defaultcontext);                 public boolean getdelegate ();    Delegate delegate public void Setdelegate (Boolean Delegate);  
    Is whether the ClassLoader will delegate the loaded task to its parent classloader, public String getInfo ();               public boolean getreloadable ();  
    Indicates whether the loader's auto-overloading public void setreloadable (Boolean reloadable) is supported;  
    public void Addpropertychangelistener (PropertyChangeListener listener);  
    public void Addrepository (String repository);  
    Public string[] Findrepositories ();                     public boolean modified (); If one or more classes in the container have been modified modified will return true public void RemovepropertychangelisteneR (Propertychangelistenerlistener);  }

By default, automatic overloading is not supported in the standard implementation-org.apache.catalina.core.standcontext of the context, so to turn on the auto-reload feature, You need to add a context element to the Server.xml file, as follows

<context path= "/myapp" docbase= "myApp" debug= "0" reloadable= "true"/>

In our program in this section, Catalina provides the implementation of the Webapploader as the Load interface. The Webapploader object contains an instance of a Org.apache.catalina.loader.WebappClassLoader class that extends the Java.neturlclassloader class.

When a container associated with a loader needs to use a servlet, or if it is to invoke a method of a servlet, the container first calls the loader's getClassLoader () method to return the class loader, and then calls the class loader's loadclass () method to load the Servlet class.

The UML class diagram is as follows:
third, Reloader interface

To support the automatic overloading of classes, the class loader needs to implement the interface.

Public interface reload{public
    void Addrepository (String respository);
    Public string[] Findrepository ();
    public boolean modified ();
}

The most important of these methods is the modified () method. The modified () method returns True if a servlet or related category in the Web application has been modified. Four, Webapploader class

An instance of this class is a Tomcat loader that is responsible for loading the classes used in the Web application. This class creates an instance of the WebappClassLoader class as its class loader. Like other components, the class also implements the lifecycle interface. In addition, the class implements the Java.lang.Runnable interface so that it can specify a thread to constantly invoke the modified () method of its class loader. If the modified () method returns an instance of True,webapploader, its associated servlet container is notified. Then there is a context instance, not a Webapploader instance, to complete the reload of the class. v. Create a class loader

To accomplish the load class, an instance of the Webapploader class uses a class loader internally.

private WebappClassLoader Createclassloader () throws Exception {//loadclass As String  
   The default is private String Loaderclass = "Org.apache.catalina.loader.WebappClassLoader";  
       Class<?> clazz = Class.forName (Loaderclass) can be changed by Setloadclass method;  

   WebappClassLoader classLoader = null; When constructing webapploader, the arguments of the constructor specify if (Parentclassloader = = null) {//would cause a classcast is the Clas s does not extend WCL, but//this is on purpose (the exception would be caught and rethrown) CLA  
       Ssloader = (WebappClassLoader) clazz.newinstance ();  
           } else {class<?>[] argtypes = {Classloader.class};  
           object[] args = {Parentclassloader};  
           constructor<?> constr = Clazz.getconstructor (argtypes);  
       ClassLoader = (WebappClassLoader) constr.newinstance (args);  
   } return ClassLoader; }  

Set up warehouses
Call Setrepositories, set web-ing/classes directory with Web-inf/lib directory

Set class Path
Related to the Jasper JSP compiler

Set access Permissions
SetPermissions can set the class loader permission to access the associated path. For example, you can only access the Web-inf/classes directory and the Web-inf/lib directory

to open a new thread to perform a reload of the class
The Webapploader class supports auto-reload functionality. If some of the classes in the Web-inf/classes directory or web/inf/lib directory are recompiled, the class is automatically re-loaded without restarting Tomcat. To implement this functionality, the Webapploader class uses a thread to periodically check the timestamp of each resource. The interval time has variable checkinterval specified.
In Tomcat4, the Webapploader class implements the Java.lang.runnable interface.

public void Run () {if (debug >= 1) log ("BACKGROUND THREAD starting"); Loop until the termination semaphore is set//entire code contained in the while loop//in front of Threaddone has been set to false//until the program closes, Threa  

           Ddone only becomes true while (!threaddone) {//Wait for our check interval threadsleep ();  

           if (!started) break;  
                   try {//Perform our modification check if (!classloader.modified ())  
           Continue  
               } catch (Exception e) {log (sm.getstring ("Webapploader.failmodifiedcheck"), e);  
           Continue  
           }//Handle a need for reloading notifycontext ();  

       Break  

   } if (debug >= 1) log ("BACKGROUND THREAD stopping"); } private void Threadsleep () {//Let program hibernate for a period of time specified by Checkinterval try {Thread.Sleep (Checkinterval * 1000L);  
       } catch (Interruptedexception e) {;  }  
   }

Once there is a change classloader.modified () will return true, calling Notifycontext () directly;

private void Notifycontext () {  
        Webappcontextnotifier notifier = new Webappcontextnotifier ();  
        (New Thread (notifier)). Start ();  
    }  
Protected class Webappcontextnotifier implements Runnable {  

        /** 
         * Perform the requested notification. 
         */Public  
        void Run () {(  
            Context) container). reload ();  
        }  
    

Webappcontextnotifier is the inner class of Webapploader.
This restarts a thread and avoids congestion. Six, WebappClassLoader class

class Cache
In order to achieve better performance, the loaded classes are cached, so the next time you use this class, you will not have to load again.

The cache is level two and is executed locally and managed by the WebappClassLoader instance.
In addition, the Java.lang.ClassLoader class maintains a vector object that holds the loaded classes, when the cache is managed by the parent class.

Each class loaded by WebappClassLoader is considered a resource. is an instance of the Org.apache.catalina.loader.ResourceEntry class that contains the byte stream representing the class file, the last modification time, and so on:

Package org.apache.catalina.loader;  
Import Java.net.URL;  
Import java.security.cert.Certificate;  
Import Java.util.jar.Manifest;  
public class Resourceentry {public  
    long lastmodifled =-1;  
    Binary content of the resource.public byte[] binarycontent = null;  
    Public Class loadedclass = null;  
    The URL source from where the object is loaded.  
    Public URL Source = null;  
    URL of the codebase from where the object is loaded.  
    Public URL CodeBase = null;  
    Public Manifest Manifest = null;  
    Public certificate[] certificates = null;  

All cached sources are stored in a HashMap called Resourceentries, where the key value is the loaded resource name, and all resources that are not found are placed in a HashMap named Notfoundresources.

Load Class
All loaded classes are cached, so the local cache needs to be checked first.
• If the class cannot be found locally, use the Findloaderclass method of the Java.langclassloader class to find the class in the cache,
• If the class cannot be found in two caches, use the system ClassLoader to avoid overwriting W from the Java EE class EB application.
• If the security Manager is used to check if the class is allowed to load, throw a ClassNotFoundException exception if the class does not allow loading.
• If the class to be loaded uses a delegate flag or the class belongs to the trigger package, the parent loader is used to load the class, and if the parent loader is NULL, it is loaded using the system loader.
• Load class from current source
• If the class is not found in the current source and the delegate flag is not used, the parent class loader is used. If the parent class loader is null, use the system loader
• If the class is still not found, throw the classnotfoundexception exception

Public class<?> loadclass (String name, Boolean resolve) throws ClassNotFoundException {if (debug >=  
    2) Log ("LoadClass (" + name + "," + Resolve + ")");  

    Class<?> clazz = null; Don ' t load classes if class loader is stopped if (!started) {//If WebappClassLoader does not start.  
        ... log ("Lifecycle error:cl stopped");  
    throw new ClassNotFoundException (name);           }//(0) Check our previously loaded local class cache Clazz = FINDLOADEDCLASS0 (name); Look at the code that's temporarily put in here. The IF (clazz! = null) {if (Debug >= 3) log ("Retu") is first found in the locally stored loaded class (HASHMAP).  
        Rning class from Cache ");  
        if (resolve) resolveclass (clazz);  
    return (Clazz); }/* Protected class<?> findLoadedClass0 (String name) {Resourceentry entry = (resourceentry) Resourceentri 
    Es.get (name); if (entry! = NULL) {return entry.loadedclass;
    } return (NULL);                  } *//(0.1) Check our previously loaded class cache Clazz = Findloadedclass (name);  
        Go to the virtual machine and look for if (clazz! = null) {if (Debug >= 3) log ("Returning class from cache");  
        if (resolve) resolveclass (clazz);  
    return (Clazz);  }//(0.2) Try loading the class with the System class loader, to prevent//the webapp from overriding  J2SE classes try {//system for system ClassLoader sun.misc.launcher$appclassloader//Load System loader first//Why use the system loader first  
    If you write a class with a full name of "Java.lang.Object," okay? You might think that the system loader doesn't load anything?  
    So what's the code behind it?  
        The loading directory of the system loader is what we look at. Clazz = System.loadclass (name);  
            if (clazz! = null) {if (resolve) resolveclass (clazz);  
        return (Clazz); }} catch (ClassNotFoundException e) {//Ignore}//For security issues I have not studied the specific code inside//(0.5) Permission To access the This class when using a SecurityManager if (SecurityManager! = null) {int i = n  
        Ame.lastindexof ('. ');  
            if (I >= 0) {try {securitymanager.checkpackageaccess (name.substring (0,i));  
                    } catch (SecurityException se) {String error = "Security violation, attempt to use" +  
                "Restricted Class:" + name;  
                SYSTEM.OUT.PRINTLN (Error);  
                Se.printstacktrace ();  
                Log (error);  
            throw new ClassNotFoundException (error); }}}//delegate defaults to False//filter if the class to be loaded is packagetrigers inside the qualified to return TRUE//the book says Packagetrigers inside the package is not allowed Loading//Can not be reflected in the code to load it?  
  Who knows why, trouble tell me//Another like the previous chapters http://localhost:8080/Primitive requested Primitiveservlet//delegate is false, filter (name) is also false Boolean delegateload = Delegate | |  

    Filter (name);  System.out.println (delegate+ "" +filter (name) + "DDD "); (1) Delegate to our parent if requested if (Delegateload) {if (Debug >= 3) log ("Del  
        Egating to Parent ClassLoader ");  
        ClassLoader loader = parent;  
        SYSTEM.OUT.PRINTLN (loader+ "loader");  
        if (loader = = NULL) loader = System;  
            try {clazz = Loader.loadclass (name);  
                if (clazz! = null) {if (Debug >= 3) Log ("Loading class from parent");  
                if (resolve) resolveclass (clazz);  
            return (Clazz);  
        }} catch (ClassNotFoundException e) {; }}//(2) Search local repositories//As for the Repositories property is in the Webapploader class Start Method Setrepositories () set//Use The various methods are as follows//findclass findclassinternal findresourceinternal//The file in Web-inf/classes is loaded first in findresourceinternal, Then load the jar file under Web-inf/lib//Last Resourceentries.put (name, entry);  
    Will put the loaded enety into the resourceentries cache if (debug >= 3) log ("Searching local repositories");  
        try {clazz = Findclass (name);  
            if (clazz! = null) {if (Debug >= 3) Log ("Loading class from local repository");  
            if (resolve) resolveclass (clazz);  
        return (Clazz);  
    }} catch (ClassNotFoundException e) {; }//The system loader is already loaded, if the program can run here, it means the system loader is not working. Why do I have to load it again//(3) Delegate to parent unconditionally if (!delegatelo  
        AD) {if (Debug >= 3) log ("Delegating to Parent ClassLoader");  
        ClassLoader loader = parent;  
        if (loader = = NULL) loader = System;  
            try {clazz = Loader.loadclass (name);  
                if (clazz! = null) {if (Debug >= 3) Log ("Loading class from parent");  
  if (resolve)                  Resolveclass (Clazz);  
            return (Clazz);  
        }} catch (ClassNotFoundException e) {;  

}}//This class is not found throw new ClassNotFoundException (name); }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.