Tomcat源碼分析-開篇(Tomcat源碼部署運行 Ant方式)


 

一、安裝配置Ant

 

(1)下載Ant

下載地址:https://ant.apache.org/bindownload.cgi  

下載完成后解壓即用。 

 

(2)配置Ant環境變量

配置ANT_HOME=F:\java\apache-ant-1.10.7

path中添加:%ANT_HOME%\bin

 

(3)查看Ant版本

命令:ant -v

到這里Ant已經安裝好了。下面就准備開始導入Tomcat源碼... 

 

 

二、導入Tomcat源碼

 

(1)下載tomcat源碼 

下載地址:https://archive.apache.org/dist/tomcat/

 

(2)修改build.properties文件

在根目錄我們可以看到有一個build.properties.default文件。將其更名為build.properties,打開,找到base.path=….;並將其改為該文件的目錄+/output。當然,你也可以隨便寫什么路徑,只要你能找到就行。

 

(3)下載相關的依賴jar

打開cmd,將進入tomcat源碼的根目錄,輸入ant 命令(這個可能會花一點時間),如圖:

下載完成后目錄如下:

 

(4)新建java項目

新建一個java Project,我自已把它命名為tomcat-src,然后將tomcat源碼下的java和test兩個文件夾以File System方式導入項目的根目錄。

 

(5)導入依賴包

ant.jar:      在你安裝的ant目錄:ANT_HOME/lib下。
jaxrpc.jar:       在eclipse下的/plugin/ javax.xml.rpc_xxx(版本號)/lib/目錄下。
org.eclipse.jdt.core_3.10.2.v20150120-1634.jar:在eclipse的plugin目錄下。
wsdl-1.6.2.jar:     eclipse的plugins目錄下。
hamcrest-2.1.jar    自行下載
junit-4.13.jar          自行下載
easymock-3.4:    自行下載
jar包可以直接從maven庫中下載  https://mvnrepository.com/ 
導入完這些包后,可能TestCookieFilter類還會報錯,這是因為CookieFilter類找不到,我們上面的輸出目錄output\build\webapps\examples\WEB-INF\classes\util中,就能找到這個類了。將其復制到TestCookieFilter的包下就OK了。

 

(6)配置啟動參數

設置vm參數:-Dcatalina.home=”源碼的路徑\output\build”
在Run Configuration里面配置如下:

到此可以直接通過啟動 Bootstrap 類中的main 方法啟動tomcat服務了。

 

結束了 !!!


 

 

三、這個Tomcat源碼項目如何啟動其它web應用?(附加內容)

 

(1)在新建的java項目中創建一個conf 目錄,並將源碼目錄下conf 的server.xml 放進去

 

(2)打開Bootstrap.java ,找到這個類的main方法,修改args參數(源碼啟動的時候 args參數為空值)

修改的這個args參數 在啟動Bootstrap 時,會去加載這個 server.xml 文件

public static void main(String args[]) {
    // 在這時修改args參數,因為直接啟動這個main方法時,args參數為空
    args = new String[]{"-config", System.getProperty("user.dir") + "\\conf\\server.xml", "start"};
    if (daemon == null) {
        // Don't set daemon until init() has completed
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.init();
        } catch (Throwable t) {
            handleThrowable(t);
            t.printStackTrace();
            return;
        }
        daemon = bootstrap;
    } else {
        // When running as a service the call to stop will be on a new
        // thread so make sure the correct class loader is used to prevent
        // a range of class not found exceptions.
        Thread.currentThread().setContextClassLoader(daemon.catalinaLoader);
    }
    // 省略若干代碼...
}

 

 

(3)修改剛才加進去的這個 server.xml 文件

代碼可以從下面進行拷貝

            <Host name="localhost" appBase="webapps" unpackWARs="true"
                autoDeploy="true">

                <!-- SingleSignOn valve, share authentication between web applications 
                    Documentation at: /docs/config/valve.html -->
                <!-- <Valve className="org.apache.catalina.authenticator.SingleSignOn" 
                    /> -->

                <!-- Access log processes all example. Documentation at: /docs/config/valve.html 
                    Note: The pattern used is equivalent to using pattern="common" -->
                <Valve className="org.apache.catalina.valves.AccessLogValve"
                    directory="logs" prefix="localhost_access_log" suffix=".txt"
                    pattern="%h %l %u %t &quot;%r&quot; %s %b" />
                <Context path="" reloadable="true"
                    docBase="D:\workspace-neno\springmvc\src\main\webapp" workDir="D:\workspace-neno\springmvc\work">
                    
                    <Loader className="org.apache.catalina.loader.MyDevLoader"
                        reloadable="true" debug="1" useSystemClassLoaderAsParent="false" />

                </Context>
            </Host>

 

(4)添加 org.apache.catalina.loader.MyDevLoader 這個類(就是上面截圖圈起來的那個類)

在 org.apache.catalina.loader 包下新建一個類,名稱為 MyDevLoader (當然可以改成你想要的名字,只要保證和server.xml 中 Loader 中的className一致就行) ;

建完類之后,直接拷貝我下面的代碼:(備注:我這里用的是tomcat8,如果是tomcat7/tomcat9 的話可能要修改一些報錯的內容

package org.apache.catalina.loader;  
  
import java.io.File;  
import java.io.FileFilter;  
import java.io.FileReader;  
import java.io.IOException;  
import java.io.LineNumberReader;  
import java.net.MalformedURLException;  
import java.net.URL;  
import java.util.ArrayList;  
import java.util.Iterator;  
import java.util.List;  
import java.util.StringTokenizer;  
import javax.servlet.ServletContext;  
import org.apache.catalina.LifecycleException;  
/**
 * 自定義DevLoader類
 * @author Administrator
 *
 */
public class MyDevLoader extends WebappLoader {  
    private static final String info = "org.apache.catalina.loader.DevLoader/1.0";  
    private String webClassPathFile = ".#webclasspath";  
    private String tomcatPluginFile = ".tomcatplugin";  
  
    public MyDevLoader() {  
    }  
  
    public MyDevLoader(ClassLoader parent) {  
        super(parent);  
    }  
  
    public void startInternal() throws LifecycleException {  
        log("Starting DevLoader");  
  
        super.startInternal();  
  
        ClassLoader cl = super.getClassLoader();  
        if (!(cl instanceof WebappClassLoader)) {  
            logError("Unable to install WebappClassLoader !");  
            return;  
        }  
        WebappClassLoader devCl = (WebappClassLoader) cl;  
  
        List webClassPathEntries = readWebClassPathEntries();  
        StringBuffer classpath = new StringBuffer();  
        for (Iterator it = webClassPathEntries.iterator(); it.hasNext();) {  
            String entry = (String) it.next();  
            File f = new File(entry);  
            if (f.exists()) {  
                if ((f.isDirectory()) && (!(entry.endsWith("/"))))  
                    f = new File(entry + "/");  
                try {  
                    URL url = f.toURL();  
  
                    // devCl.addRepository(url.toString());  
                    devCl.addURL(url);  
                    classpath.append(f.toString() + File.pathSeparatorChar);  
                    log("added " + url.toString());  
                } catch (MalformedURLException e) {  
                    logError(entry + " invalid (MalformedURL)");  
                }  
            } else {  
                logError(entry + " does not exist !");  
            }  
        }  
  
        String cp = (String) getServletContext().getAttribute("org.apache.catalina.jsp_classpath");  
        StringTokenizer tokenizer = new StringTokenizer(cp, File.pathSeparatorChar + "");  
        while (tokenizer.hasMoreTokens()) {  
            String token = tokenizer.nextToken();  
  
            if ((token.charAt(0) == '/') && (token.charAt(2) == ':')) {  
                token = token.substring(1);  
            }  
            classpath.append(token + File.pathSeparatorChar);  
        }  
  
        getServletContext().setAttribute("org.apache.catalina.jsp_classpath", classpath.toString());  
        log("JSPCompiler Classpath = " + classpath);  
    }  
  
    protected void log(String msg) {  
        System.out.println("[DevLoader] " + msg);  
    }  
  
    protected void logError(String msg) {  
        System.err.println("[DevLoader] Error: " + msg);  
    }  
  
    protected List readWebClassPathEntries() {  
        List rc = null;  
  
        File prjDir = getProjectRootDir();  
        if (prjDir == null)  
            return new ArrayList();  
  
        log("projectdir=" + prjDir.getAbsolutePath());  
  
        rc = loadWebClassPathFile(prjDir);  
  
        if (rc == null)  
            rc = new ArrayList();  
        return rc;  
    }  
  
    protected File getProjectRootDir() {  
        File rootDir = getWebappDir();  
        FileFilter filter = new FileFilter() {  
            public boolean accept(File file) {  
                return (file.getName().equalsIgnoreCase(webClassPathFile) || file.getName().equalsIgnoreCase(tomcatPluginFile));  
            }  
        };  
        while (rootDir != null) {  
            File[] files = rootDir.listFiles(filter);  
            if ((files != null) && (files.length >= 1))  
                return files[0].getParentFile();  
  
            rootDir = rootDir.getParentFile();  
        }  
        return null;  
    }  
  
    protected List loadWebClassPathFile(File prjDir) {  
        File cpFile = new File(prjDir, this.webClassPathFile);  
        if (cpFile.exists()) {  
            FileReader reader = null;  
            try {  
                List rc = new ArrayList();  
                reader = new FileReader(cpFile);  
                LineNumberReader lr = new LineNumberReader(reader);  
                String line = null;  
                while ((line = lr.readLine()) != null) {  
                    line = line.replace('\\', '/');  
                    rc.add(line);  
                }  
                return rc;  
            } catch (IOException ioEx) {  
                if (reader != null)  
                    ;  
                return null;  
            }  
        }  
        return null;  
    }  
  
    protected ServletContext getServletContext() {  
        // return ((Context) getContainer()).getServletContext();  
        return this.getContext().getServletContext();  
    }  
  
    protected File getWebappDir() {  
        File webAppDir = new File(getServletContext().getRealPath("/"));  
        return webAppDir;  
    }  
}  

 

(5)啟動 BootStrap 中的main方法

這樣你其它的web項目就啟動了,這個就相當於eclipse插件中那個貓的圖標按鈕功能!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM