Tomcat 学习笔记

如何创建一个简单的Servlet

添加Servlet的jar包

    <dependencies>
        <dependency>
            <groupId>Javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
    </dependencies>

创建ServletTest.java

创建一个ServletTest.java文件如下

package com.test;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

 
@WebServlet(urlPatterns = "/test")
public class ServletTest extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().print("aaa");
    }
}

这个是Servlet3.0的写法,可以通过注解的方式代替xml

这样一个简单的Servlet就创建好了。

到现在的话,直接打包的会报错

Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.2:war (default-war) on project servlettest: Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1]

因为在打war包的时候,必须有web.xml,可是我们没有创建,在这里使用maven-war的插件即可

  <build>
        <plugins>
          <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-war-plugin</artifactId>
              <version>3.2.0</version>
          </plugin>
        </plugins>
    </build>

在pom.xml 中添加这段会帮我们自动添加web.xml

到这就可以执行mvn install命令了,然后我们把war文件放到tomcat 的webapps路径下即可;
在这里插入图片描述

参考地址: (https://www.ibm.com/developerworks/cn/java/j-lo-servlet30/index.html)

Tomcat 的几种部署方式

  1. 将war包放到复制到目录中$CATALINA_BASE/webapps/

    这种形式, 当Tomcat启动时,它会自动将Web应用程序归档文件扩展为其解压缩的形式,并且会根据子目录名称为应用程序分配上下文路径。如果用这种方式部署,后续如果向更改了程序代码,必须重启才可以生效。

    这种方式也就是上面我们测试的方式。

  2. 在tomcat的server.xml中添加context元素

    第1种方式是最简单的,也是入门的时候最常见的。

    接下来就是这种,在servet.xml中添加如下代码

    在这里插入图片描述

    <Context path="/aaa" docBase="E:\webapp\servlettest\target\servlettest-1.0-SNAPSHOT">
    </Context>
    

    docBase:web应用程序的根目录

    path: Web应用程序的上下文路径,与每个请求URI的开头匹配,以选择适当的Web应用程序进行处理.

    配置完,启动tomcat 即可访问

  3. $CATALINA_BASE/conf/catalina/localhost下新建xml

    第二种方式看似简单,省去了复制war包的过程,在server.xml中配置难免显得杂乱,所以我们可以将context元素的内容在$CATALINA_BASE/conf/catalina/localhost 下新建一个xml, 这个xml的名称则就是上下文的路径,如果context中也同样配置了path ,则还是以名称为主。

    <?xml version="1.0" encoding="UTF-8"?>	
    	<Context path="/aaa" docBase="E:\webapp\servlettest\target\servlettest-1.0-SNAPSHOT">
    			</Context>
    

    在这里插入图片描述
    在这里插入图片描述

当然 配置context元素的方式也是直接热部署的

更多context属性说明:http://tomcat.apache.org/tomcat-8.5-doc/config/context.html

Tomcat Maven 插件

大家有没有感觉到,如上开发的时候,不管如何处理,貌似都很麻烦,我们必须下载tomcat,还得打包部署或者配置tomcat中的xml文件,稍微有一个地方出错,就特别耗费时间,然而tomcat maven 就让我们在开发的时候省了很多时间。

  1. ​ 在pom.xml添加如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.servlet</groupId>
        <artifactId>servlettest</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>war</packaging>
        <dependencies>
            <dependency>
                <groupId>Javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.1.0</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>
        <build>
            <plugins>
              <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-war-plugin</artifactId>
                  <version>3.2.0</version>
              </plugin>
                
                <!--**** 在此位置添加tomcat 插件 **** -->
                <plugin>
                    <!--这个是配置说明地址请大家参考:http://tomcat.apache.org/maven-plugin-trunk/run-mojo-features.html-->
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <configuration>
                         <port>8080</port>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>
    

    添加之后,插件就会下载,稍微等下就好。

    如果是idea 的话 配置下tomcat7:run即可启动

在这里插入图片描述

maven插件配置说明地址请大家参考:http://tomcat.apache.org/maven-plugin-trunk/run-mojo-features.html

maven tomcat 深入的了解

​ 看到maven tomcat 如此的方便,就对这个插件产生的浓厚的好奇心。

​ 首先我们打包下,

 <plugin>
                <!--http://tomcat.apache.org/maven-plugin-trunk/run-mojo-features.html-->
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <configuration>
                     <port>8080</port>
                </configuration>
                <executions>
                    <execution>
                        <id>tomcat-run</id>
                        <goals>
                            <goal>exec-war-only</goal>
                        </goals>
                        <phase>package</phase>
                        <configuration>
                            <path>/</path>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

更改下pom.xml中的配置 然后打包下,然后在target文件夹中发现了有一个jar
在这里插入图片描述

这个jar 是可以直接java -jar 执行的,那么既然的jar,他就一定有一个入口方法,我就从入口方法下手,看看这个是如何运行的。

​ 果然在MANIFEST.MF 文件中发现了这段

Manifest-Version: 1.0
Main-Class: org.apache.tomcat.maven.runner.Tomcat7RunnerCli

很明显,这就是他的入口。

那么在pom.xml 添加jar的依赖,查看下入口到底长什么样子。

  <dependency>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
        </dependency>

注:maven 插件其实也是一个jar文件而已。直接添加依赖即可;

在这里插入图片描述

找到main入口之后,依次发现代码没什么

大概梳理了下代码

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.apache.tomcat.maven.runner;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.Map.Entry;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class Tomcat7RunnerCli {
    public static final String STAND_ALONE_PROPERTIES_FILENAME = "tomcat.standalone.properties";
    static Option httpPort;
    static Option httpsPort;
    static Option ajpPort;
    static Option serverXmlPath;
    static Option resetExtract;
    static Option help;
    static Option debug;
    static Option sysProps;
    static Option clientAuth;
    static Option keyAlias;
    static Option obfuscate;
    static Option httpProtocol;
    static Option extractDirectory;
    static Option loggerName;
    static Option uriEncoding;
    static Options options;

    public Tomcat7RunnerCli() {
    }

    public static void main(String[] args) throws Exception {
		// 创建解析器
        CommandLineParser parser = new GnuParser();
        CommandLine line = null;

        try {
			// 解析参数,例如:spring boot 启动方式  java -jar demo.jar --server.port=8080   通过server.port 设置端口号   不过这里是httpPort  
            line = parser.parse(options, args);
        } catch (ParseException var8) {
            System.err.println("Parsing failed.  Reason: " + var8.getMessage());
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(getCmdLineSyntax(), options);
            System.exit(1);
        }

        if (line.hasOption(help.getOpt())) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(getCmdLineSyntax(), options);
            System.exit(0);
        }

        if (line.hasOption(obfuscate.getOpt())) {
            System.out.println(PasswordUtil.obfuscate(line.getOptionValue(obfuscate.getOpt())));
            System.exit(0);
        }
		// 创建Tomcat对象
        Tomcat7Runner tomcat7Runner = new Tomcat7Runner();
        tomcat7Runner.runtimeProperties = buildStandaloneProperties();
        if (line.hasOption(serverXmlPath.getOpt())) {
            tomcat7Runner.serverXmlPath = line.getOptionValue(serverXmlPath.getOpt());
        }
		// 获取端口号
        String port = tomcat7Runner.runtimeProperties.getProperty("httpPort");
        if (port != null) {
            tomcat7Runner.httpPort = Integer.parseInt(port);
        }
		// 获取启动时的端口号,启动时设置的端口号优先
        if (line.hasOption(httpPort.getOpt())) {
            tomcat7Runner.httpPort = Integer.parseInt(line.getOptionValue(httpPort.getOpt()));
        }

        if (line.hasOption(httpsPort.getOpt())) {
            tomcat7Runner.httpsPort = Integer.parseInt(line.getOptionValue(httpsPort.getOpt()));
        }
		// ajp端口号
        if (line.hasOption(ajpPort.getOpt())) {
            tomcat7Runner.ajpPort = Integer.parseInt(line.getOptionValue(ajpPort.getOpt()));
        }

        if (line.hasOption(resetExtract.getOpt())) {
            tomcat7Runner.resetExtract = true;
        }

        if (line.hasOption(debug.getOpt())) {
            tomcat7Runner.debug = true;
        }

        if (line.hasOption(httpProtocol.getOpt())) {
            tomcat7Runner.httpProtocol = line.getOptionValue(httpProtocol.getOpt());
        }

        if (line.hasOption(sysProps.getOpt())) {
            Properties systemProperties = line.getOptionProperties(sysProps.getOpt());
            if (systemProperties != null && !systemProperties.isEmpty()) {
                Iterator i$ = systemProperties.entrySet().iterator();

                while(i$.hasNext()) {
                    Entry<Object, Object> sysProp = (Entry)i$.next();
                    System.setProperty((String)sysProp.getKey(), (String)sysProp.getValue());
                }
            }
        }

        if (line.hasOption(clientAuth.getOpt())) {
            tomcat7Runner.clientAuth = clientAuth.getOpt();
        }

        if (line.hasOption(keyAlias.getOpt())) {
            tomcat7Runner.keyAlias = line.getOptionValue(keyAlias.getOpt());
        }

        if (line.hasOption(extractDirectory.getOpt())) {
            tomcat7Runner.extractDirectory = line.getOptionValue(extractDirectory.getOpt());
        }
		//loggerName 日志配置
        if (line.hasOption(loggerName.getOpt())) {
            tomcat7Runner.loggerName = line.getOptionValue(loggerName.getOpt());
        }
		//uriEncoding 编码配置
        if (line.hasOption(uriEncoding.getOpt())) {
            tomcat7Runner.uriEncoding = line.getOptionValue(uriEncoding.getOpt());
        }
		// 一直到这里, 都是关于tomcat的一些配置,这些相对无关紧要,
		// run 方法请看下一段代码
        tomcat7Runner.run();
    }

    private static Properties buildStandaloneProperties() throws IOException {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("tomcat.standalone.properties");
        Properties properties = new Properties();
        properties.load(is);
        return properties;
    }

    public static String getCmdLineSyntax() {
        return "java -jar [path to your exec war jar]";
    }

    static {
        OptionBuilder.withArgName("httpPort");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription("http port to use");
        httpPort = OptionBuilder.create("httpPort");
        OptionBuilder.withArgName("httpsPort");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription("https port to use");
        httpsPort = OptionBuilder.create("httpsPort");
        OptionBuilder.withArgName("ajpPort");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription("ajp port to use");
        ajpPort = OptionBuilder.create("ajpPort");
        OptionBuilder.withArgName("serverXmlPath");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription("server.xml to use, optional");
        serverXmlPath = OptionBuilder.create("serverXmlPath");
        OptionBuilder.withArgName("resetExtract");
        OptionBuilder.withDescription("clean previous extract directory");
        resetExtract = OptionBuilder.create("resetExtract");
        OptionBuilder.withLongOpt("help");
        OptionBuilder.withDescription("help");
        help = OptionBuilder.create('h');
        OptionBuilder.withLongOpt("debug");
        OptionBuilder.withDescription("debug");
        debug = OptionBuilder.create('X');
        OptionBuilder.withDescription("use value for given property");
        OptionBuilder.hasArgs();
        OptionBuilder.withDescription("key=value");
        OptionBuilder.withValueSeparator();
        sysProps = OptionBuilder.create('D');
        OptionBuilder.withArgName("clientAuth");
        OptionBuilder.withDescription("enable client authentication for https");
        clientAuth = OptionBuilder.create("clientAuth");
        OptionBuilder.withArgName("keyAlias");
        OptionBuilder.hasArgs();
        OptionBuilder.withDescription("alias from keystore for ssl");
        keyAlias = OptionBuilder.create("keyAlias");
        OptionBuilder.withArgName("password");
        OptionBuilder.hasArgs();
        OptionBuilder.withDescription("obfuscate the password and exit");
        obfuscate = OptionBuilder.create("obfuscate");
        OptionBuilder.withArgName("httpProtocol");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription("http protocol to use: HTTP/1.1 or org.apache.coyote.http11.Http11NioProtocol");
        httpProtocol = OptionBuilder.create("httpProtocol");
        OptionBuilder.withArgName("extractDirectory");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription("path to extract war content, default value: .extract");
        extractDirectory = OptionBuilder.create("extractDirectory");
        OptionBuilder.withArgName("loggerName");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription("logger to use: slf4j to use slf4j bridge on top of jul");
        loggerName = OptionBuilder.create("loggerName");
        OptionBuilder.withArgName("uriEncoding");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription("connector uriEncoding default ISO-8859-1");
        uriEncoding = OptionBuilder.create("uriEncoding");
        options = new Options();
        options.addOption(httpPort).addOption(httpsPort).addOption(ajpPort).addOption(serverXmlPath).addOption(resetExtract).addOption(help).addOption(debug).addOption(sysProps).addOption(httpProtocol).addOption(clientAuth).addOption(keyAlias).addOption(obfuscate).addOption(extractDirectory).addOption(loggerName).addOption(uriEncoding);
    }
}

上面是Tomcat7Runner.java 的代码

下面贴上Tomcat7Runner.java 的代码 Tomcat7Runner中代码太多, 主要贴出了run方法,有兴趣的可以自己去看看



package org.apache.tomcat.maven.runner;

public class Tomcat7Runner  {

    public static final String USE_SERVER_XML_KEY = "useServerXml";
    public static final String WARS_KEY = "wars";
    public static final String ARCHIVE_GENERATION_TIMESTAMP_KEY = "generationTimestamp";
    public static final String ENABLE_NAMING_KEY = "enableNaming";
    public static final String ACCESS_LOG_VALVE_FORMAT_KEY = "accessLogValveFormat";
    public static final String CODE_SOURCE_CONTEXT_PATH = "codeSourceContextPath";
    public static final String HTTP_PROTOCOL_KEY = "connectorhttpProtocol";
    public static final String HTTP_PORT_KEY = "httpPort";
    public int httpPort;
    public int httpsPort;
    public int ajpPort;
    public String serverXmlPath;
    public Properties runtimeProperties;
    public boolean resetExtract;
    public boolean debug = false;
    public String clientAuth = "false";
    public String keyAlias = null;
    public String httpProtocol;
    public String extractDirectory = ".extract";
    public File extractDirectoryFile;
    public String codeSourceContextPath = null;
    public File codeSourceWar = null;
    public String loggerName;
    Catalina container;
    Tomcat tomcat;
    String uriEncoding = "ISO-8859-1";
    Map<String, String> webappWarPerContext = new HashMap();

    public Tomcat7Runner() {
    }
public void run() throws Exception {
        PasswordUtil.deobfuscateSystemProps();
        if(this.loggerName != null && this.loggerName.length() > 0) {
            this.installLogger(this.loggerName);
        }

        this.extractDirectoryFile = new File(this.extractDirectory);
        this.debugMessage("use extractDirectory:" + this.extractDirectoryFile.getPath());
        boolean archiveTimestampChanged = false;
		// 获取当前目录tomcat_executable_archive.timestamp配置文件,这个文件在servlettest-1.0-SNAPSHOT-war-exec.jar 中打开就可以发现
		// 为了方便我贴上配置文件的内容,突然一看配置文件我很是懵逼。
		// #created by Apache Tomcat Maven plugin
		//#Tue Apr 16 21:39:05 CST 2019
		//generationTimestamp=1555421945264
		//accessLogValveFormat=%h %l %u %t %r %s %b %I %D
		//enableNaming=false
		//useServerXml=false
		//wars=.war|/
		//connectorhttpProtocol=HTTP/1.1
        File timestampFile = new File(this.extractDirectoryFile, ".tomcat_executable_archive.timestamp");
        Properties timestampProps = this.loadProperties(timestampFile);
        String wars;
        if(timestampFile.exists()) {
            wars = timestampProps.getProperty("generationTimestamp");
            if(wars != null) {
                long timestamp = Long.parseLong(wars);
                archiveTimestampChanged = Long.parseLong(this.runtimeProperties.getProperty("generationTimestamp")) > timestamp;
                this.debugMessage("read timestamp from file " + wars + ", archiveTimestampChanged: " + archiveTimestampChanged);
            }
        }

        this.codeSourceContextPath = this.runtimeProperties.getProperty("codeSourceContextPath");
        if(this.codeSourceContextPath != null && !this.codeSourceContextPath.isEmpty()) {
            this.codeSourceWar = (File)AccessController.doPrivileged(new PrivilegedAction<File>() {
                public File run() {
                    try {
                        File src = new File(Tomcat7Runner.class.getProtectionDomain().getCodeSource().getLocation().toURI());
                        if(src.getName().endsWith(".war")) {
                            return src;
                        }

                        Tomcat7Runner.this.debugMessage("ERROR: Code source is not a war file, ignoring.");
                    } catch (URISyntaxException var2) {
                        Tomcat7Runner.this.debugMessage("ERROR: Could not find code source. " + var2.getMessage());
                    }

                    return null;
                }
            });
        }

        if(this.extractDirectoryFile.exists() && !this.resetExtract && !archiveTimestampChanged) {
            wars = this.runtimeProperties.getProperty("wars");
            this.populateWebAppWarPerContext(wars);
        } else {
            this.extract();
            if(archiveTimestampChanged || !timestampFile.exists()) {
                timestampProps.put("generationTimestamp", this.runtimeProperties.getProperty("generationTimestamp"));
                this.saveProperties(timestampProps, timestampFile);
            }
        }
		// 以上都是对配置文件做的处理
		// 下面这几行看到特别熟悉,这应该就是创建基本的tomcat目录
        (new File(this.extractDirectory, "conf")).mkdirs();
        (new File(this.extractDirectory, "logs")).mkdirs();
        (new File(this.extractDirectory, "webapps")).mkdirs();
        (new File(this.extractDirectory, "work")).mkdirs();
        File tmpDir = new File(this.extractDirectory, "temp");
        tmpDir.mkdirs();
        System.setProperty("java.io.tmpdir", tmpDir.getAbsolutePath());
        System.setProperty("catalina.base", this.extractDirectoryFile.getAbsolutePath());
        System.setProperty("catalina.home", this.extractDirectoryFile.getAbsolutePath());
        if(this.serverXmlPath == null && !this.useServerXml()) {
            this.tomcat = new Tomcat() {
				//看到这里,想到之前在server.xml中配置的xml信息是不是一目了然
				//<Context path="/aaa" docBase="E:\webapp\servlettest\target\servlettest-1.0-SNAPSHOT">
				//</Context>
                public Context addWebapp(Host host, String url, String name, String path) {
                    Context ctx = new StandardContext();
                    ctx.setName(name);
                    ctx.setPath(url);
                    ctx.setDocBase(path);
                    ContextConfig ctxCfg = new ContextConfig();
                    ctx.addLifecycleListener(ctxCfg);
                    ctxCfg.setDefaultWebXml((new File(Tomcat7Runner.this.extractDirectory, "conf/web.xml")).getAbsolutePath());
                    if(host == null) {
                        this.getHost().addChild(ctx);
                    } else {
                        host.addChild(ctx);
                    }

                    return ctx;
                }
            };
            if(this.enableNaming()) {
                System.setProperty("catalina.useNaming", "true");
                this.tomcat.enableNaming();
            }

            this.tomcat.getHost().setAppBase((new File(this.extractDirectory, "webapps")).getAbsolutePath());
            String connectorHttpProtocol = this.runtimeProperties.getProperty("connectorhttpProtocol");
            if(this.httpProtocol != null && this.httpProtocol.trim().length() > 0) {
                connectorHttpProtocol = this.httpProtocol;
            }
			
            this.debugMessage("use connectorHttpProtocol:" + connectorHttpProtocol);
			//以下在代码在server.xml中基本都能找到对应配置例如下面这个
            if(this.httpPort > 0) {
				//这里对应servet.xml 的这段配置
				//<Connector port="8080" protocol="HTTP/1.1"
               //        connectionTimeout="20000"
               //				redirectPort="8443" />  
			   //
                Connector connector = new Connector(connectorHttpProtocol);
                connector.setPort(this.httpPort);
                if(this.httpsPort > 0) {
                    connector.setRedirectPort(this.httpsPort);
                }

                connector.setURIEncoding(this.uriEncoding);
                this.tomcat.getService().addConnector(connector);
                this.tomcat.setConnector(connector);
            }

            AccessLogValve alv = new AccessLogValve();
            alv.setDirectory((new File(this.extractDirectory, "logs")).getAbsolutePath());
            alv.setPattern(this.runtimeProperties.getProperty("accessLogValveFormat"));
            this.tomcat.getHost().getPipeline().addValve(alv);
            Connector httpsConnector;
            String baseDir;
            String context;
            if(this.httpsPort > 0) {
                httpsConnector = new Connector(connectorHttpProtocol);
                httpsConnector.setPort(this.httpsPort);
                httpsConnector.setSecure(true);
                httpsConnector.setProperty("SSLEnabled", "true");
                httpsConnector.setProperty("sslProtocol", "TLS");
                httpsConnector.setURIEncoding(this.uriEncoding);
                String keystoreFile = System.getProperty("javax.net.ssl.keyStore");
                baseDir = System.getProperty("javax.net.ssl.keyStorePassword");
                context = System.getProperty("javax.net.ssl.keyStoreType", "jks");
                if(keystoreFile != null) {
                    httpsConnector.setAttribute("keystoreFile", keystoreFile);
                }

                if(baseDir != null) {
                    httpsConnector.setAttribute("keystorePass", baseDir);
                }

                httpsConnector.setAttribute("keystoreType", context);
                String truststoreFile = System.getProperty("javax.net.ssl.trustStore");
                String truststorePass = System.getProperty("javax.net.ssl.trustStorePassword");
                String truststoreType = System.getProperty("javax.net.ssl.trustStoreType", "jks");
                if(truststoreFile != null) {
                    httpsConnector.setAttribute("truststoreFile", truststoreFile);
                }

                if(truststorePass != null) {
                    httpsConnector.setAttribute("truststorePass", truststorePass);
                }

                httpsConnector.setAttribute("truststoreType", truststoreType);
                httpsConnector.setAttribute("clientAuth", this.clientAuth);
                httpsConnector.setAttribute("keyAlias", this.keyAlias);
                this.tomcat.getService().addConnector(httpsConnector);
                if(this.httpPort <= 0) {
                    this.tomcat.setConnector(httpsConnector);
                }
            }

            if(this.ajpPort > 0) {
                httpsConnector = new Connector("org.apache.coyote.ajp.AjpProtocol");
                httpsConnector.setPort(this.ajpPort);
                httpsConnector.setURIEncoding(this.uriEncoding);
                this.tomcat.getService().addConnector(httpsConnector);
            }

            Iterator i$ = this.webappWarPerContext.entrySet().iterator();

            while(i$.hasNext()) {
                Entry<String, String> entry = (Entry)i$.next();
                baseDir = null;
                context = null;
                Context context;
                if(((String)entry.getKey()).equals("/")) {
                    baseDir = (new File(this.extractDirectory, "webapps/ROOT.war")).getAbsolutePath();
                    context = this.tomcat.addWebapp("", baseDir);
                } else {
                    baseDir = (new File(this.extractDirectory, "webapps/" + (String)entry.getValue())).getAbsolutePath();
                    context = this.tomcat.addWebapp((String)entry.getKey(), baseDir);
                }

                URL contextFileUrl = this.getContextXml(baseDir);
                if(contextFileUrl != null) {
                    context.setConfigFile(contextFileUrl);
                }
            }

            if(this.codeSourceWar != null) {
                String baseDir = (new File(this.extractDirectory, "webapps/" + this.codeSourceWar.getName())).getAbsolutePath();
                Context context = this.tomcat.addWebapp(this.codeSourceContextPath, baseDir);
                URL contextFileUrl = this.getContextXml(baseDir);
                if(contextFileUrl != null) {
                    context.setConfigFile(contextFileUrl);
                }
            }

            this.tomcat.start();
            Runtime.getRuntime().addShutdownHook(new Tomcat7Runner.TomcatShutdownHook());
        } else {
            this.container = new Catalina();
            this.container.setUseNaming(this.enableNaming());
            if(this.serverXmlPath != null && (new File(this.serverXmlPath)).exists()) {
                this.container.setConfig(this.serverXmlPath);
            } else {
                this.container.setConfig((new File(this.extractDirectory, "conf/server.xml")).getAbsolutePath());
            }

            this.container.start();
        }
		//  大家知道正常情况下一个main方法执行完了结束了
		// 可是这也是一个main方法却不会结束,就是这行代码可以使main方法处与等待状态
        this.waitIndefinitely();
    }
    
}

说实话,看了这两段代码,发现tomcat 插件如此的简单.看代码前要先熟悉tomcat架构,要不然看的很懵逼

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叁滴水

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值