Tomcat从零开始(六)容器

来源:互联网 发布:暴风雪数据 编辑:程序博客网 时间:2024/05/22 05:34

第六课:

       容器,我们首先来理解一下容器的概念是什么。我做一个比喻,就像一个公司,它就是一个容器,它包含了很多部门。同样部门也是一个容器,他也包括员工。

       现在说说tomcat的容器,根据官方的文档。Tomcat一共包含4种容器,分别是Engine,host,context,wrapper.  其实比较推荐多看看documentation,其实很多知识都是从documentation中学到的,其实一手的学习能力很重要。就像你到了一个新公司,你要学习他们的业务,这个是没有教程的。都要靠你自己理解。这里先简单的介绍一下各个容器都是干什么的,Engine:Catalina的servlet引擎,Host:N个Context的虚拟主机,Context:表示一个Web应用,一个context包含一个或多个wrapper。

Wrapper:表示一个独立的servlet      行了,不多说。回到容器的问题上,既然engine,host,context,wrapper.是容器,那么他们肯定得 继承Container接口。这个是可以在org.apche.catalina包里自己证明。而org.apache.catalina.core包里,我们可以发现各种容器的StrandardXXX的实现,这个实现肯定得 实现这4个接口,同时看一下源码。

public final class StandardWrapper

   extends ContainerBase

implements ServletConfig,Wrapper

我们发现它实现了Wrapper接口,至于这个ServletConfig接口现在不多说,同时继承了ContainerBase抽象类。

public abstract class ContainerBase

implementsContainer, Lifecycle, Pipeline

这个Lifecycle,其实可以简要的说  就是父亲控制儿子的启动和停止。Pipeline则是流水线。这部分先不多说,这次主要是介绍pipeline,应该下一节课,我会比较详细的介绍一下每个容器都包含什么,当然我只是介绍一下,这个暂时不需要太深入的理解。

先看看pipeline这东西,在ContainerBase这个类里的invoke方法中,调用了pipeline的invoke,下面看一下pipeline的代码。

    public void invoke(Request request, Response response)        throws IOException, ServletException {        // Invoke the first Valve in this pipeline for this request        (new StandardPipelineValveContext()).invokeNext(request, response);    }

我们可以看见,它 new 了一个StandardPipelineValveContext这个类,而这个类正是一个内部类。我们来看看他的代码

        public void invokeNext(Request request, Response response)            throws IOException, ServletException {            int subscript = stage;            stage = stage + 1;            // Invoke the requested Valve for the current request thread            if (subscript < valves.length) {                valves[subscript].invoke(request, response, this);            } else if ((subscript == valves.length) && (basic != null)) {                basic.invoke(request, response, this);            } else {                throw new ServletException                    (sm.getString("standardPipeline.noValve"));            }        }

我们可以看到,用一个stage进行标记,去确定调用到了第几个 valve,之后就像递归一样的调用完所有的valve。打个比方,这个就好像filter,而这种调用方式就像 filter Chain一样。

这章就这么样了。剩下就是自己的服务器的代码。明日给大家上传上来。

原创粉丝点击