目录结构
/bin:二进制文件目录,存放脚本文件
/conf:存放Tomcat服务器的各种全局配置文件,其中最重要的是server.xml和web.xml
/lib:存放Tomcat服务器以及所有web应用都可以访问的jar文件
/logs:存放Tomcat执行时的日志文件
/work:存放JSP编译后产生的class文件
/webapps:Tomcat的主要Web发布目录,默认情况下把Web应用文件放于此目录
部署方式
1.直接放入到webapps目录下
2.在conf/server.xml中的<host>节点下新增
<Context docBase="D:\project\yanxiaohui" path="/yanxiaohui" reloadable="true"/>
docBase表示加载的内容地址 path 访问路径
3.conf\Catalina\localhost目录下创建yanxiaohui.xml
<Context docBase="D:\project\yanxiaohui" reloadable="true"/>
注意不需要 path 默认是.xml文件名称
4.使用内嵌入Tomcat方式(SpringBoot底层原理实现)
架构模式
其基本组件如下:
Server:
服务器的意思,代表整个tomcat服务器,一个tomcat只有一个Server
Service:
Server中的一个逻辑功能层, 一个Server可以包含多个Service
Connector:
称作连接器,是Service的核心组件之一,一个Service可以有多个Connector,主要是连接客户端请求;
Container:
Service的另一个核心组件,按照层级有Engine,Host,Context,Wrapper四种,一个Service只有一个Engine,其主要
作用是执行业务逻辑;
源码分析
客户端发起请求时,会交由server中services启动的connector监听对应的协议和端口,采用多线程处理请求,最终
交由container处理
当我们在运行Tomcat的时候,实际上在启动Bootstrap.main函数
如何java中内嵌tomcat8
Maven依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.4.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>8.5.28</version>
</dependency>
<!-- Tomcat对jsp支持 -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>8.5.16</version>
</dependency>
</dependencies>
核心代码
public class TomcatTest {
public static void main(String[] args) throws LifecycleException, ServletException {
// 创建tomcat服务器
Tomcat tomcatServer = new Tomcat();
// 设定端口号
tomcatServer.setPort(9090);
// 设置上下文路径
StandardContext ctx = (StandardContext) tomcatServer.addWebapp("/", new File("src/main").getAbsolutePath());
// 禁止项目重入加载
ctx.setReloadable(false);
// 设置读取class文件地址
File additionWebInfClasses = new File("target/classes");
// 设置我们webRoot
WebResourceRoot resources = new StandardRoot(ctx);
resources.addPreResources(new DirResourceSet(resources, "/target/classes", additionWebInfClasses.getAbsolutePath(), "/"));
// 开启我们的tomcat
tomcatServer.start();
// tomcat等待接受请求
tomcatServer.getServer().await();
}
}
总结
1.tomcat的脚本文件中指定了以java的方式启动MainClass为BootStarp
2.BootStarp按照反射去创建Catalina,其包含tomcat的各大组件(连接器,线程池,交换机等)
3.Catalina的init中使用责任链设计模式循环初始化对应的组件
4.Catalina的load指定加载conf/server.xml中的配置信息,也会将所有的Wrapper放入servlet容器
5.初始化好之后对外进行访问,按照请求的url去匹配对应的servlet
扫描二维码关注公众号,回复:
11205477 查看本文章