Tomcat是一个JSP/Servlet容器。其做为Servlet容器,有三种工做模式:独立的Servlet容器、进程内的Servlet容器和进程外的Servlet容器。html
Tomcat是一个基于组件的服务器,它的构成组件都是可配置的,其中最外层的是Catalina servlet容器,其余组件按照必定的格式要求配置在这个顶层容器中。
Tomcat的各类组件都是在Tomcat安装目录下的/conf/server.xml文件中配置的。前端
Tomcat目录java
tomcat
|---bin:存放启动和关闭tomcat脚本mysql
|---conf:存放不一样的配置文件(server.xml和web.xml);
|---doc:存放Tomcat文档;
|---lib/japser/common:存放Tomcat运行须要的库文件(JARS);
|---logs:存放Tomcat执行时的LOG文件;
|---src:存放Tomcat的源代码;
|---webapps:Tomcat的主要Web发布目录(包括应用程序示例);
|---work:存放jsp编译后产生的class文件;web
TomCat配置文件sql
Tomcat架构及经常使用的组件:数据库
一、Server组件express
如上面示例文件中定义的:apache
<Server port=”8005” shutdown=”SHUTDOWN”>设计模式
这会让Tomcat6启动一个server实例(即一个JVM),它监听在8005端口以接收shutdown命令,使用 telnet 链接8005 端口能够直接执行 SHUTDOWN 命令来关闭 Tomcat。各Server的定义不能使用同一个端口,这意味着若是在同一个物理机上启动了多个Server实例,必须配置它们使用不一样的端口。这个端口的定义用于为管理员提供一个关闭此实例的便捷途径,所以,管理员能够直接telnet至此端口使用SHUTDOWN命令关闭此实例。不过,基于安全角度的考虑,这一般不容许远程进行。
Server的相关属性:
className: 用于实现此Server容器的彻底限定类的名称,默认为org.apache.catalina.core.StandardServer;
port: 接收shutdown指令的端口,默认仅容许经过本机访问,默认为8005;
shutdown:发往此Server用于实现关闭tomcat实例的命令字符串,默认为SHUTDOWN;
二、Service组件:
Service主要用于关联一个引擎和与此引擎相关的链接器,每一个链接器经过一个特定的端口和协议接收入站请求交将其转发相当联的引擎进行处理。困此,Service要包含一个引擎、一个或多个链接器。
如上面示例中的定义:
<Service name=”Catalina”>
这定义了一个名为Catalina的Service,此名字也会在产生相关的日志信息时记录在日志文件当中。
Service相关的属性:
className: 用于实现service的类名,通常都是org.apache.catalina.core.StandardService。
name:此服务的名称,默认为Catalina;
三、Connector组件:
进入Tomcat的请求能够根据Tomcat的工做模式分为以下两类:
Tomcat做为应用程序服务器:请求来自于前端的web服务器,这多是Apache, IIS, Nginx等;
Tomcat做为独立服务器:请求来自于web浏览器;
Tomcat应该考虑工做情形并为相应情形下的请求分别定义好须要的链接器才能正确接收来自于客户端的请求。一个引擎能够有一个或多个链接器,以适应多种请求方式。
定义链接器可使用多种属性,有些属性也只适用于某特定的链接器类型。通常说来,常见于server.xml中的链接器类型一般有4种:
1) HTTP链接器 2) SSL链接器 3) AJP 1.3链接器 4) proxy链接器
如上面示例server.xml中定义的HTTP链接器:
<Connector port=”8080″ protocol=”HTTP/1.1″ maxThreads=”150″ connectionTimeout=”20000″ redirectPort=”8443″/>
定义链接器时能够配置的属性很是多,但一般定义HTTP链接器时必须定义的属性只有“port“,定义AJP链接器时必须定义的属性只有”protocol”,由于默认的协议为HTTP。如下为经常使用属性的说明:
下面是一个定义了多个属性的SSL链接器:
<Connector port=”8443″ maxThreads=”150″ minSpareThreads=”25″ maxSpareThreads=”75″ enableLookups=”false” acceptCount=”100″ debug=”0″ scheme=”https” secure=”true” clientAuth=”false” sslProtocol=”TLS” />
四、Engine组件:
Engine是Servlet处理器的一个实例,即servlet引擎,默认为定义在server.xml中的Catalina。Engine须要defaultHost属性来为其定义一个接收全部发往非明肯定义虚拟主机的请求的host组件。如前面示例中定义的:
<Engine name=”Catalina” defaultHost=”localhost”>
经常使用的属性定义:
defaultHost:Tomcat支持基于FQDN的虚拟主机,这些虚拟主机能够经过在Engine容器中定义多个不一样的Host组件来实现;但若是此引擎的链接器收到一个发往非非明肯定义虚拟主机的请求时则须要将此请求发往一个默认的虚拟主机进行处理,所以,在Engine中定义的多个虚拟主机的主机名称中至少要有一个跟defaultHost定义的主机名称同名;
name:Engine组件的名称,用于日志和错误信息记录时区别不一样的引擎;
Engine容器中能够包含Realm、Host、Listener和Valve子容器。
五、Host组件:
位于Engine容器中用于接收请求并进行相应处理的主机或虚拟主机,如前面示例中的定义:
<Host name=”localhost” appBase=”webapps” unpackWARs=”true” autoDeploy=”true” xmlValidation=”false” xmlNamespaceAware=”false”> </Host>
经常使用属性说明:
虚拟主机定义示例:
<Engine name=”Catalina” defaultHost=”localhost”> <Host name=”localhost” appBase=”webapps”> <Context path=”” docBase=”ROOT”/> <Context path=”/bbs” docBase=”/web/bss” #path路径是定义在defaultHost背后的 reloadable=”true” crossContext=”true”/> </Host> <Host name=”mail.magedu.com” appBase=”/web/mail”> <Context path=”” docBase=”ROOT”/> </Host> </Engine>
主机别名定义:
若是一个主机有两个或两个以上的主机名,额外的名称都可以以别名的形式进行定义,以下:
<Host name=”www.ttlsa.com” appBase=”webapps” unpackWARs=”true”> <Alias>feiyu.com</Alias> </Host>
六、Context组件:
Context在某些意义上相似于apache中的路径别名,一个Context定义用于标识tomcat实例中的一个Web应用程序;以下面的定义:
<!– Tomcat Root Context –> <Context path=”” docBase=”/web/webapps”/> <!– buzzin webapp –> <Context path=”/bbs” docBase=”/web/threads/bbs” reloadable=”true”> </Context> <!– chat server –> <Context path=”/chat” docBase=”/web/chat”/> <!– darian web –> <Context path=”/darian” docBase=”darian”/>
在Tomcat6中,每个context定义也可使用一个单独的XML文件进行,其文件的目录为$CATALINA_HOME/conf//。能够用于Context中的XML元素有Loader,Manager,Realm,Resources和WatchedResource。
经常使用的属性定义有:
七、Realm组件:
一个Realm表示一个安全上下文,它是一个受权访问某个给定Context的用户列表和某用户所容许切换的角色相关定义的列表。所以,Realm就像是一个用户和组相关的数据库。定义Realm时唯一必需要提供的属性是classname,它是Realm的多个不一样实现,用于表示此Realm认证的用户及角色等认证信息的存放位置。
八、Valve组件:
Valve相似于过滤器,它能够工做于Engine和Host/Context之间、Host和Context之间以及Context和Web应用程序的某资源之间。一个容器内能够创建多个Valve,并且Valve定义的次序也决定了它们生效的次序。Tomcat6中实现了多种不一样的Valve:
下面是一个常见的使用UserDatabase的配置:
<Realm className=”org.apache.catalina.realm.UserDatabaseRealm” resourceName=”UserDatabase”/>
下面是一个使用JDBC方式获取用户认证信息的配置:
<Realm className=”org.apache.catalina.realm.JDBCRealm” debug=”99″ driverName=”org.gjt.mm.mysql.Driver” connectionURL=”jdbc:mysql://localhost/authority” connectionName=”test” connectionPassword=”test” userTable=”users” userNameCol=”user_name” userCredCol=”user_pass” userRoleTable=”user_roles” roleNameCol=”role_name” />
八、Valve组件:
Valve相似于过滤器,它能够工做于Engine和Host/Context之间、Host和Context之间以及Context和Web应用程序的某资源之间。一个容器内能够创建多个Valve,并且Valve定义的次序也决定了它们生效的次序。Tomcat6中实现了多种不一样的Valve:
RemoteHostValve和RemoteAddrValve能够分别用来实现基于主机名称和基于IP地址的访问控制,控制自己能够经过allow或deny来进行定义,这有点相似于Apache的访问控制功能;以下面的Valve则实现了仅容许本机访问/probe:
<Context path=”/probe” docBase=”probe”> <Valve className=”org.apache.catalina.valves.RemoteAddrValve” allow=”127\.0\.0\.1″/> </Context>
<Server> //顶层类元素,能够包括多个Service <Service> //顶层类元素,可包含一个Engine,多个Connecter <Connector> //链接器类元素,表明通讯接口 <Engine> //容器类元素,为特定的Service组件处理客户请求,要包含多个Host <Host> //容器类元素,为特定的虚拟主机组件处理客户请求,可包含多个Context <Context> //容器类元素,为特定的Web应用处理全部的客户请求 </Context> </Host> </Engine> </Connector> </Service> </Server>
server.xml源码以下
<?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. --> <!-- 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="8005" 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="8080" 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="8009" 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 "%r" %s %b" /> </Host> </Engine> </Service> </Server>
由上可得出Tomcat的体系结构:
图一:Tomcat的体系结构
由上图可看出Tomca的心脏是两个组件:Connecter和Container。一个Container能够选择多个Connecter,多个Connector和一个Container就造成了一个Service。Service能够对外提供服务,而Server服务器控制整个Tomcat的生命周期。
组件的生命线“Lifecycle”
Service 和 Server 管理它下面组件的生命周期。
Tomcat 中组件的生命周期是经过 Lifecycle 接口来控制的,组件只要继承这个接口并实现其中的方法就能够统一被拥有它的组件控制了,这样一层一层的直到一个最高级的组件就能够控制 Tomcat 中全部组件的生命周期,这个最高的组件就是 Server,而控制 Server 的是 Startup,也就是您启动和关闭 Tomcat。
一个Connecter将在某个指定的端口上侦听客户请求,接收浏览器的发过来的 tcp 链接请求,建立一个 Request 和 Response 对象分别用于和请求端交换数据,而后会产生一个线程来处理这个请求并把产生的 Request 和 Response 对象传给处理Engine(Container中的一部分),从Engine出得到响应并返回客户。
Tomcat中有两个经典的Connector,一个直接侦听来自Browser的HTTP请求,另一个来自其余的WebServer请求。Cotote HTTP/1.1 Connector在端口8080处侦听来自客户Browser的HTTP请求,Coyote JK2 Connector在端口8009处侦听其余Web Server的Servlet/JSP请求。
Connector 最重要的功能就是接收链接请求而后分配线程让 Container 来处理这个请求,因此这必然是多线程的,多线程的处理是 Connector 设计的核心。
Container的体系结构以下:
图二:Container的体系结构
Container是容器的父接口,该容器的设计用的是典型的责任链的设计模式,它由四个自容器组件构成,分别是Engine、Host、Context、Wrapper。这四个组件是负责关系,存在包含关系。一般一个Servlet class对应一个Wrapper,若是有多个Servlet定义多个Wrapper,若是有多个Wrapper就要定义一个更高的Container,如Context。
Context 还能够定义在父容器 Host 中,Host 不是必须的,可是要运行 war 程序,就必需要 Host,由于 war 中必有 web.xml 文件,这个文件的解析就须要 Host 了,若是要有多个 Host 就要定义一个 top 容器 Engine 了。而 Engine 没有父容器了,一个 Engine 表明一个完整的 Servlet 引擎。
Tomcat 还有其它重要的组件,如安全组件 security、logger 日志组件、session、mbeans、naming 等其它组件。这些组件共同为 Connector 和 Container 提供必要的服务。
图三:Tomcat Server处理一个HTTP请求的过程
一、用户点击网页内容,请求被发送到本机端口8080,被在那里监听的Coyote HTTP/1.1 Connector得到。
二、Connector把该请求交给它所在的Service的Engine来处理,并等待Engine的回应。
三、Engine得到请求localhost/test/index.jsp,匹配全部的虚拟主机Host。
四、Engine匹配到名为localhost的Host(即便匹配不到也把请求交给该Host处理,由于该Host被定义为该Engine的默认主机),名为localhost的Host得到请求/test/index.jsp,匹配它所拥有的全部的Context。Host匹配到路径为/test的Context(若是匹配不到就把该请求交给路径名为“ ”的Context去处理)。
五、path=“/test”的Context得到请求/index.jsp,在它的mapping table中寻找出对应的Servlet。Context匹配到URL PATTERN为*.jsp的Servlet,对应于JspServlet类。
六、构造HttpServletRequest对象和HttpServletResponse对象,做为参数调用JspServlet的doGet()或doPost().执行业务逻辑、数据存储等程序。
七、Context把执行完以后的HttpServletResponse对象返回给Host。
八、Host把HttpServletResponse对象返回给Engine。
九、Engine把HttpServletResponse对象返回Connector。
十、Connector把HttpServletResponse对象返回给客户Browser。