Tomcat分析-启动过程

  • Server是Tomcat最顶层的容器
  • Service用于提供服务
  • Connector用于处理连接相关的事情,并提供Socket与request和response的转换
  • Container用于封装和管理Servlet,以及具体处理request请求

一、启动过程

  • Catalina:是Tomcat的管理类
  • Bootstrap:是Tomcat的入口类

1、Bootstrap启动过程

 
image.png
  • 第465行bootstrap.init();
 
image.png

main方法作用

  • init方法初始化了ClassLoader,并用ClassLoader创建了Catalina实例,然后赋值给catalinaDaemon变量
  • 根据main方法args参数执行对应的生命周期方法,以start方法为例
 
image.png
  • 利用反射调用Catalina的start方法,实际上就是走的Catalina类的生命周期方法

说到生命周期方法,就得知道那几个方法是生命周期方法了

  • start
  • stop
  • load
  • 还有一个重要的方法:await,他不是生命周期方法,但是他让主线程不会退出。

2、Catalina启动过程

<?xml version="1.0" encoding="UTF-8"?>

<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="9000" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector port="9001" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation. The default
         SSLImplementation will depend on the presence of the APR/native
         library and the useOpenSSL attribute of the
         AprLifecycleListener.
         Either JSSE or OpenSSL style configuration may be used regardless of
         the SSLImplementation selected. JSSE style configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true">
        <SSLHostConfig>
            <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
         This connector uses the APR/native implementation which always uses
         OpenSSL for TLS.
         Either JSSE or OpenSSL style configuration may be used. OpenSSL style
         configuration is used below.
    -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
               maxThreads="150" SSLEnabled="true" >
        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
        <SSLHostConfig>
            <Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
                         certificateFile="conf/localhost-rsa-cert.pem"
                         certificateChainFile="conf/localhost-rsa-chain.pem"
                         type="RSA" />
        </SSLHostConfig>
    </Connector>
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="9002" protocol="AJP/1.3" redirectPort="8443" />


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <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" />

      </Host>
    </Engine>
  </Service>
</Server>
<?xml version="1.0" encoding="UTF-8"?>

<!-- The contents of this file will be loaded for each web application -->
<Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
</Context>
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  version="3.1">

  <!-- ======================== Introduction ============================== -->
  <!-- This document defines default values for *all* web applications      -->
  <!-- loaded into this instance of Tomcat.  As each application is         -->
  <!-- deployed, this file is processed, followed by the                    -->
  <!-- "/WEB-INF/web.xml" deployment descriptor from your own               -->
  <!-- applications.                                                        -->
  <!--                                                                      -->
  <!-- WARNING:  Do not configure application-specific resources here!      -->
  <!-- They should go in the "/WEB-INF/web.xml" file in your application.   -->


  <!-- ================== Built In Servlet Definitions ==================== -->


  <!-- The default servlet for all web applications, that serves static     -->
  <!-- resources.  It processes all requests that are not mapped to other   -->
  <!-- servlets with servlet mappings (defined either here or in your own   -->
  <!-- web.xml file).  This servlet supports the following initialization   -->
  <!-- parameters (default values are in square brackets):                  -->
  <!--                                                                      -->
  <!--   debug               Debugging detail level for messages logged     -->
  <!--                       by this servlet. Useful values are 0, 1, and   -->
  <!--                       11 where higher values mean more detail. [0]   -->
  <!--                                                                      -->
  <!--   fileEncoding        Encoding to be used to read static resources   -->
  <!--                       [platform default]                             -->
  <!--                                                                      -->
  <!--   input               Input buffer size (in bytes) when reading      -->
  <!--                       resources to be served.  [2048]                -->
  <!--                                                                      -->
  <!--   listings            Should directory listings be produced if there -->
  <!--                       is no welcome file in this directory?  [false] -->
  <!--                       WARNING: Listings for directories with many    -->
  <!--                       entries can be slow and may consume            -->
  <!--                       significant proportions of server resources.   -->
  <!--                                                                      -->
  <!--   output              Output buffer size (in bytes) when writing     -->
  <!--                       resources to be served.  [2048]                -->
  <!--                                                                      -->
  <!--   readonly            Is this context "read only", so HTTP           -->
  <!--                       commands like PUT and DELETE are               -->
  <!--                       rejected?  [true]                              -->
  <!--                                                                      -->
  <!--   readmeFile          File to display together with the directory    -->
  <!--                       contents. [null]                               -->
  <!--                                                                      -->
  <!--   sendfileSize        If the connector used supports sendfile, this  -->
  <!--                       represents the minimal file size in KB for     -->
  <!--                       which sendfile will be used. Use a negative    -->
  <!--                       value to always disable sendfile.  [48]        -->
  <!--                                                                      -->
  <!--   useAcceptRanges     Should the Accept-Ranges header be included    -->
  <!--                       in responses where appropriate? [true]         -->
  <!--                                                                      -->
  <!--  For directory listing customization. Checks localXsltFile, then     -->
  <!--  globalXsltFile, then defaults to original behavior.                 -->
  <!--                                                                      -->
  <!--   localXsltFile       Make directory listings an XML doc and         -->
  <!--                       pass the result to this style sheet residing   -->
  <!--                       in that directory. This overrides              -->
  <!--                       contextXsltFile and globalXsltFile[null]       -->
  <!--                                                                      -->
  <!--   contextXsltFile     Make directory listings an XML doc and         -->
  <!--                       pass the result to this style sheet which is   -->
  <!--                       relative to the context root. This overrides   -->
  <!--                       globalXsltFile[null]                           -->
  <!--                                                                      -->
  <!--   globalXsltFile      Site wide configuration version of             -->
  <!--                       localXsltFile. This argument must either be an -->
  <!--                       absolute or relative (to either                -->
  <!--                       $CATALINA_BASE/conf or $CATALINA_HOME/conf)    -->
  <!--                       path that points to a location below either    -->
  <!--                       $CATALINA_BASE/conf (checked first) or         -->
  <!--                       $CATALINA_HOME/conf (checked second).[null]    -->
  <!--                                                                      -->
  <!--   showServerInfo      Should server information be presented in the  -->
  <!--                       response sent to clients when directory        -->
  <!--                       listings is enabled? [true]                    -->

    <servlet>
        <servlet-name>default</servlet-name>
        <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>0</param-value>
        </init-param>
        <init-param>
            <param-name>listings</param-name>
            <param-value>false</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>


  <!-- The JSP page compiler and execution servlet, which is the mechanism  -->
  <!-- used by Tomcat to support JSP pages.  Traditionally, this servlet    -->
  <!-- is mapped to the URL pattern "*.jsp".  This servlet supports the     -->
  <!-- following initialization parameters (default values are in square    -->
  <!-- brackets):                                                           -->
  <!--                                                                      -->
  <!--   checkInterval       If development is false and checkInterval is   -->
  <!--                       greater than zero, background compilations are -->
  <!--                       enabled. checkInterval is the time in seconds  -->
  <!--                       between checks to see if a JSP page (and its   -->
  <!--                       dependent files) needs to  be recompiled. [0]  -->
  <!--                                                                      -->
  <!--   classdebuginfo      Should the class file be compiled with         -->
  <!--                       debugging information?  [true]                 -->
  <!--                                                                      -->
  <!--   classpath           What class path should I use while compiling   -->
  <!--                       generated servlets?  [Created dynamically      -->
  <!--                       based on the current web application]          -->
  <!--                                                                      -->
  <!--   compiler            Which compiler Ant should use to compile JSP   -->
  <!--                       pages.  See the jasper documentation for more  -->
  <!--                       information.                                   -->
  <!--                                                                      -->
  <!--   compilerSourceVM    Compiler source VM. [1.7]                      -->
  <!--                                                                      -->
  <!--   compilerTargetVM    Compiler target VM. [1.7]                      -->
  <!--                                                                      -->
  <!--   development         Is Jasper used in development mode? If true,   -->
  <!--                       the frequency at which JSPs are checked for    -->
  <!--                       modification may be specified via the          -->
  <!--                       modificationTestInterval parameter. [true]     -->
  <!--                                                                      -->
  <!--   displaySourceFragment                                              -->
  <!--                       Should a source fragment be included in        -->
  <!--                       exception messages? [true]                     -->
  <!--                                                                      -->
  <!--   dumpSmap            Should the SMAP info for JSR45 debugging be    -->
  <!--                       dumped to a file? [false]                      -->
  <!--                       False if suppressSmap is true                  -->
  <!--                                                                      -->
  <!--   enablePooling       Determines whether tag handler pooling is      -->
  <!--                       enabled. This is a compilation option. It will -->
  <!--                       not alter the behaviour of JSPs that have      -->
  <!--                       already been compiled. [true]                  -->
  <!--                                                                      -->
  <!--   engineOptionsClass  Allows specifying the Options class used to    -->
  <!--                       configure Jasper. If not present, the default  -->
  <!--                       EmbeddedServletOptions will be used.           -->
  <!--                       This option is ignored when running under a    -->
  <!--                       SecurityManager.                               -->
  <!--                                                                      -->
  <!--   errorOnUseBeanInvalidClassAttribute                                -->
  <!--                       Should Jasper issue an error when the value of -->
  <!--                       the class attribute in an useBean action is    -->
  <!--                       not a valid bean class?  [true]                -->
  <!--                                                                      -->
  <!--   fork                Tell Ant to fork compiles of JSP pages so that -->
  <!--                       a separate JVM is used for JSP page compiles   -->
  <!--                       from the one Tomcat is running in. [true]      -->
  <!--                                                                      -->
  <!--   genStringAsCharArray                                               -->
  <!--                       Should text strings be generated as char       -->
  <!--                       arrays, to improve performance in some cases?  -->
  <!--                       [false]                                        -->
  <!--                                                                      -->
  <!--   ieClassId           The class-id value to be sent to Internet      -->
  <!--                       Explorer when using <jsp:plugin> tags.         -->
  <!--                       [clsid:8AD9C840-044E-11D1-B3E9-00805F499D93]   -->
  <!--                                                                      -->
  <!--   javaEncoding        Java file encoding to use for generating java  -->
  <!--                       source files. [UTF8]                           -->
  <!--                                                                      -->
  <!--   keepgenerated       Should we keep the generated Java source code  -->
  <!--                       for each page instead of deleting it? [true]   -->
  <!--                                                                      -->
  <!--   mappedfile          Should we generate static content with one     -->
  <!--                       print statement per input line, to ease        -->
  <!--                       debugging?  [true]                             -->
  <!--                                                                      -->
  <!--   maxLoadedJsps       The maximum number of JSPs that will be loaded -->
  <!--                       for a web application. If more than this       -->
  <!--                       number of JSPs are loaded, the least recently  -->
  <!--                       used JSPs will be unloaded so that the number  -->
  <!--                       of JSPs loaded at any one time does not exceed -->
  <!--                       this limit. A value of zero or less indicates  -->
  <!--                       no limit. [-1]                                 -->
  <!--                                                                      -->
  <!--   jspIdleTimeout      The amount of time in seconds a JSP can be     -->
  <!--                       idle before it is unloaded. A value of zero    -->
  <!--                       or less indicates never unload. [-1]           -->
  <!--                                                                      -->
  <!--   modificationTestInterval                                           -->
  <!--                       Causes a JSP (and its dependent files) to not  -->
  <!--                       be checked for modification during the         -->
  <!--                       specified time interval (in seconds) from the  -->
  <!--                       last time the JSP was checked for              -->
  <!--                       modification. A value of 0 will cause the JSP  -->
  <!--                       to be checked on every access.                 -->
  <!--                       Used in development mode only. [4]             -->
  <!--                                                                      -->
  <!--   recompileOnFail     If a JSP compilation fails should the          -->
  <!--                       modificationTestInterval be ignored and the    -->
  <!--                       next access trigger a re-compilation attempt?  -->
  <!--                       Used in development mode only and is disabled  -->
  <!--                       by default as compilation may be expensive and -->
  <!--                       could lead to excessive resource usage.        -->
  <!--                       [false]                                        -->
  <!--                                                                      -->
  <!--   scratchdir          What scratch directory should we use when      -->
  <!--                       compiling JSP pages?  [default work directory  -->
  <!--                       for the current web application]               -->
  <!--                       This option is ignored when running under a    -->
  <!--                       SecurityManager.                               -->
  <!--                                                                      -->
  <!--   suppressSmap        Should the generation of SMAP info for JSR45   -->
  <!--                       debugging be suppressed?  [false]              -->
  <!--                                                                      -->
  <!--   trimSpaces          Should white spaces in template text between   -->
  <!--                       actions or directives be trimmed?  [false]     -->
  <!--                                                                      -->
  <!--   xpoweredBy          Determines whether X-Powered-By response       -->
  <!--                       header is added by generated servlet.  [false] -->
  <!--                                                                      -->
  <!--   strictQuoteEscaping When scriptlet expressions are used for        -->
  <!--                       attribute values, should the rules in JSP.1.6  -->
  <!--                       for the escaping of quote characters be        -->
  <!--                       strictly applied? [true]                       -->
  <!--                                                                      -->
  <!--   quoteAttributeEL    When EL is used in an attribute value on a     -->
  <!--                       JSP page should the rules for quoting of       -->
  <!--                       attributes described in JSP.1.6 be applied to  -->
  <!--                       the expression? [true]                         -->

    <servlet>
        <servlet-name>jsp</servlet-name>
        <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
        <init-param>
            <param-name>fork</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>xpoweredBy</param-name>
            <param-value>false</param-value>
        </init-param>
        <load-on-startup>3</load-on-startup>
    </servlet>


  <!-- NOTE: An SSI Filter is also available as an alternative SSI          -->
  <!-- implementation. Use either the Servlet or the Filter but NOT both.   -->
  <!--                                                                      -->
  <!-- Server Side Includes processing servlet, which processes SSI         -->
  <!-- directives in HTML pages consistent with similar support in web      -->
  <!-- servers like Apache.  Traditionally, this servlet is mapped to the   -->
  <!-- URL pattern "*.shtml".  This servlet supports the following          -->
  <!-- initialization parameters (default values are in square brackets):   -->
  <!--                                                                      -->
  <!--   buffered            Should output from this servlet be buffered?   -->
  <!--                       (0=false, 1=true)  [0]                         -->
  <!--                                                                      -->
  <!--   debug               Debugging detail level for messages logged     -->
  <!--                       by this servlet.  [0]                          -->
  <!--                                                                      -->
  <!--   expires             The number of seconds before a page with SSI   -->
  <!--                       directives will expire.  [No default]          -->
  <!--                                                                      -->
  <!--   isVirtualWebappRelative                                            -->
  <!--                       Should "virtual" paths be interpreted as       -->
  <!--                       relative to the context root, instead of       -->
  <!--                       the server root? [false]                       -->
  <!--                                                                      -->
  <!--   inputEncoding       The encoding to assume for SSI resources if    -->
  <!--                       one is not available from the resource.        -->
  <!--                       [Platform default]                             -->
  <!--                                                                      -->
  <!--   outputEncoding      The encoding to use for the page that results  -->
  <!--                       from the SSI processing. [UTF-8]               -->
  <!--                                                                      -->
  <!--   allowExec           Is use of the exec command enabled? [false]    -->

<!--
    <servlet>
        <servlet-name>ssi</servlet-name>
        <servlet-class>
          org.apache.catalina.ssi.SSIServlet
        </servlet-class>
        <init-param>
          <param-name>buffered</param-name>
          <param-value>1</param-value>
        </init-param>
        <init-param>
          <param-name>debug</param-name>
          <param-value>0</param-value>
        </init-param>
        <init-param>
          <param-name>expires</param-name>
          <param-value>666</param-value>
        </init-param>
        <init-param>
          <param-name>isVirtualWebappRelative</param-name>
          <param-value>false</param-value>
        </init-param>
        <load-on-startup>4</load-on-startup>
    </servlet>
-->


  <!-- Common Gateway Includes (CGI) processing servlet, which supports     -->
  <!-- execution of external applications that conform to the CGI spec      -->
  <!-- requirements.  Typically, this servlet is mapped to the URL pattern  -->
  <!-- "/cgi-bin/*", which means that any CGI applications that are         -->
  <!-- executed must be present within the web application.  This servlet   -->
  <!-- supports the following initialization parameters (default values     -->
  <!-- are in square brackets):                                             -->
  <!--                                                                      -->
  <!--   cgiPathPrefix        The CGI search path will start at             -->
  <!--                        webAppRootDir + File.separator + this prefix. -->
  <!--                        If not set, then webAppRootDir is used.       -->
  <!--                        Recommended value: WEB-INF/cgi                -->
  <!--                                                                      -->
  <!--   executable           Name of the executable used to run the        -->
  <!--                        script. [perl]                                -->
  <!--                                                                      -->
  <!--   envHttpHeaders       A regular expression used to select the HTTP  -->
  <!--                        headers passed to the CGI process as          -->
  <!--                        environment variables. Note that headers are  -->
  <!--                        converted to upper case before matching and   -->
  <!--                        that the entire header name must match the    -->
  <!--                        pattern.                                      -->
  <!--                        [ACCEPT[-0-9A-Z]*|CACHE-CONTROL|COOKIE|HOST|  -->
  <!--                         IF-[-0-9A-Z]*|REFERER|USER-AGENT]            -->
  <!--                                                                      -->
  <!--   parameterEncoding    Name of parameter encoding to be used with    -->
  <!--                        CGI servlet.                                  -->
  <!--                        [System.getProperty("file.encoding","UTF-8")] -->
  <!--                                                                      -->
  <!--   passShellEnvironment Should the shell environment variables (if    -->
  <!--                        any) be passed to the CGI script? [false]     -->
  <!--                                                                      -->
  <!--   stderrTimeout        The time (in milliseconds) to wait for the    -->
  <!--                        reading of stderr to complete before          -->
  <!--                        terminating the CGI process. [2000]           -->

<!--
    <servlet>
        <servlet-name>cgi</servlet-name>
        <servlet-class>org.apache.catalina.servlets.CGIServlet</servlet-class>
        <init-param>
          <param-name>cgiPathPrefix</param-name>
          <param-value>WEB-INF/cgi</param-value>
        </init-param>
        <load-on-startup>5</load-on-startup>
    </servlet>
-->


  <!-- ================ Built In Servlet Mappings ========================= -->


  <!-- The servlet mappings for the built in servlets defined above.  Note  -->
  <!-- that, by default, the CGI and SSI servlets are *not* mapped.  You    -->
  <!-- must uncomment these mappings (or add them to your application's own -->
  <!-- web.xml deployment descriptor) to enable these services              -->

    <!-- The mapping for the default servlet -->
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- The mappings for the JSP servlet -->
    <servlet-mapping>
        <servlet-name>jsp</servlet-name>
        <url-pattern>*.jsp</url-pattern>
        <url-pattern>*.jspx</url-pattern>
    </servlet-mapping>

    <!-- The mapping for the SSI servlet -->
<!--
    <servlet-mapping>
        <servlet-name>ssi</servlet-name>
        <url-pattern>*.shtml</url-pattern>
    </servlet-mapping>
-->

    <!-- The mapping for the CGI Gateway servlet -->

<!--
    <servlet-mapping>
        <servlet-name>cgi</servlet-name>
        <url-pattern>/cgi-bin/*</url-pattern>
    </servlet-mapping>
-->


  <!-- ================== Built In Filter Definitions ===================== -->

  <!-- A filter that sets various security related HTTP Response headers.   -->
  <!-- This filter supports the following initialization parameters         -->
  <!-- (default values are in square brackets):                             -->
  <!--                                                                      -->
  <!--   hstsEnabled         Should the HTTP Strict Transport Security      -->
  <!--                       (HSTS) header be added to the response? See    -->
  <!--                       RFC 6797 for more information on HSTS. [true]  -->
  <!--                                                                      -->
  <!--   hstsMaxAgeSeconds   The max age value that should be used in the   -->
  <!--                       HSTS header. Negative values will be treated   -->
  <!--                       as zero. [0]                                   -->
  <!--                                                                      -->
  <!--   hstsIncludeSubDomains                                              -->
  <!--                       Should the includeSubDomains parameter be      -->
  <!--                       included in the HSTS header.                   -->
  <!--                                                                      -->
  <!--   antiClickJackingEnabled                                            -->
  <!--                       Should the anti click-jacking header           -->
  <!--                       X-Frame-Options be added to every response?    -->
  <!--                       [true]                                         -->
  <!--                                                                      -->
  <!--   antiClickJackingOption                                             -->
  <!--                       What value should be used for the header. Must -->
  <!--                       be one of DENY, SAMEORIGIN, ALLOW-FROM         -->
  <!--                       (case-insensitive). [DENY]                     -->
  <!--                                                                      -->
  <!--   antiClickJackingUri IF ALLOW-FROM is used, what URI should be      -->
  <!--                       allowed? []                                    -->
  <!--                                                                      -->
  <!--   blockContentTypeSniffingEnabled                                    -->
  <!--                       Should the header that blocks content type     -->
  <!--                       sniffing be added to every response? [true]    -->
<!--
    <filter>
        <filter-name>httpHeaderSecurity</filter-name>
        <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
        <async-supported>true</async-supported>
    </filter>
-->

  <!-- A filter that sets character encoding that is used to decode -->
  <!-- parameters in a POST request -->
<!--
    <filter>
        <filter-name>setCharacterEncodingFilter</filter-name>
        <filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <async-supported>true</async-supported>
    </filter>
-->

  <!-- A filter that triggers request parameters parsing and rejects the    -->
  <!-- request if some parameters were skipped because of parsing errors or -->
  <!-- request size limitations.                                            -->
<!--
    <filter>
        <filter-name>failedRequestFilter</filter-name>
        <filter-class>
          org.apache.catalina.filters.FailedRequestFilter
        </filter-class>
        <async-supported>true</async-supported>
    </filter>
-->


  <!-- NOTE: An SSI Servlet is also available as an alternative SSI         -->
  <!-- implementation. Use either the Servlet or the Filter but NOT both.   -->
  <!--                                                                      -->
  <!-- Server Side Includes processing filter, which processes SSI          -->
  <!-- directives in HTML pages consistent with similar support in web      -->
  <!-- servers like Apache.  Traditionally, this filter is mapped to the    -->
  <!-- URL pattern "*.shtml", though it can be mapped to "*" as it will     -->
  <!-- selectively enable/disable SSI processing based on mime types. For   -->
  <!-- this to work you will need to uncomment the .shtml mime type         -->
  <!-- definition towards the bottom of this file.                          -->
  <!-- The contentType init param allows you to apply SSI processing to JSP -->
  <!-- pages, javascript, or any other content you wish.  This filter       -->
  <!-- supports the following initialization parameters (default values are -->
  <!-- in square brackets):                                                 -->
  <!--                                                                      -->
  <!--   contentType         A regex pattern that must be matched before    -->
  <!--                       SSI processing is applied.                     -->
  <!--                       [text/x-server-parsed-html(;.*)?]              -->
  <!--                                                                      -->
  <!--   debug               Debugging detail level for messages logged     -->
  <!--                       by this servlet.  [0]                          -->
  <!--                                                                      -->
  <!--   expires             The number of seconds before a page with SSI   -->
  <!--                       directives will expire.  [No default]          -->
  <!--                                                                      -->
  <!--   isVirtualWebappRelative                                            -->
  <!--                       Should "virtual" paths be interpreted as       -->
  <!--                       relative to the context root, instead of       -->
  <!--                       the server root? [false]                       -->
  <!--                                                                      -->
  <!--   allowExec           Is use of the exec command enabled? [false]    -->

<!--
    <filter>
        <filter-name>ssi</filter-name>
        <filter-class>
          org.apache.catalina.ssi.SSIFilter
        </filter-class>
        <init-param>
          <param-name>contentType</param-name>
          <param-value>text/x-server-parsed-html(;.*)?</param-value>
        </init-param>
        <init-param>
          <param-name>debug</param-name>
          <param-value>0</param-value>
        </init-param>
        <init-param>
          <param-name>expires</param-name>
          <param-value>666</param-value>
        </init-param>
        <init-param>
          <param-name>isVirtualWebappRelative</param-name>
          <param-value>false</param-value>
        </init-param>
    </filter>
-->


  <!-- ==================== Built In Filter Mappings ====================== -->

  <!-- The mapping for the HTTP header security Filter -->
<!--
    <filter-mapping>
        <filter-name>httpHeaderSecurity</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
    </filter-mapping>
-->

  <!-- The mapping for the Set Character Encoding Filter -->
<!--
    <filter-mapping>
        <filter-name>setCharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
-->

  <!-- The mapping for the Failed Request Filter -->
<!--
    <filter-mapping>
        <filter-name>failedRequestFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
-->

  <!-- The mapping for the SSI Filter -->
<!--
    <filter-mapping>
        <filter-name>ssi</filter-name>
        <url-pattern>*.shtml</url-pattern>
    </filter-mapping>
-->


  <!-- ==================== Default Session Configuration ================= -->
  <!-- You can set the default session timeout (in minutes) for all newly   -->
  <!-- created sessions by modifying the value below.                       -->

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>


  <!-- ===================== Default MIME Type Mappings =================== -->
  <!-- When serving static resources, Tomcat will automatically generate    -->
  <!-- a "Content-Type" header based on the resource's filename extension,  -->
  <!-- based on these mappings.  Additional mappings can be added here (to  -->
  <!-- apply to all web applications), or in your own application's web.xml -->
  <!-- deployment descriptor.                                               -->
  <!-- Note: Extensions are always matched in a case-insensitive manner.    -->

    <mime-mapping>
        <extension>123</extension>
        <mime-type>application/vnd.lotus-1-2-3</mime-type>
    </mime-mapping>

  <!-- ==================== Default Welcome File List ===================== -->
  <!-- When a request URI refers to a directory, the default servlet looks  -->
  <!-- for a "welcome file" within that directory and, if present, to the   -->
  <!-- corresponding resource URI for display.                              -->
  <!-- If no welcome files are present, the default servlet either serves a -->
  <!-- directory listing (see default servlet configuration on how to       -->
  <!-- customize) or returns a 404 status, depending on the value of the    -->
  <!-- listings setting.                                                    -->
  <!--                                                                      -->
  <!-- If you define welcome files in your own application's web.xml        -->
  <!-- deployment descriptor, that list *replaces* the list configured      -->
  <!-- here, so be sure to include any of the default values that you wish  -->
  <!-- to use within your application.                                       -->

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

重要的几个配置文件

  • server.xml
  • web.xml
 
image.png
  • Catalina的init方法是调用了Server的init方法(其实是LifecycleBase的init方法,Server类继承LifecycleBase
  • Server对象是通过开源的项目Digester解析conf/server.xml文件来完成的

3、Server的启动过程

  • Server的默认实现是standardServer,standardServer的启动是执行standardServer的initInternal和startInternal方法,在initInternal和startInternal方法中又分别调用了service的init方法和start方法
 
image.png
  • await方法(保证主线程不会退出)
 
image.png
 
image.png
 
image.png

解释说明:

  • port等于-2,则直接退出,不进入循环
  • port等于-1,进入一个while循环,没有break跳出循环,只能通过stopAwait标志来退出,stopAwait只有调用了stop方法才会设置为true
  • port为其他值,会进入一个while循环,同时会有一个ServerSocket来监听port端口,如果接收到SHUTDOWN命令,则跳出循环
 - server.xml
<Server port="9000" shutdown="SHUTDOWN">

Demo

 
image.png
 
image.png

4、Service启动过程

 
image.png
  • standardService的startInternal方法主要调用了engine、executors、mapperListener、connector的start方法
  • mapperListener(不太熟悉):是Mapper的监听器,可以监听container的变化
  • executors:是用在connectors管理线程的的线程池
 
image.png

5、Tomcat启动流程图

 
image.png


作者:橙小张
链接:https://www.jianshu.com/p/e968660f4ecf
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
原文地址:https://www.cnblogs.com/zgq123456/p/10150660.html