Servlet和Tomcat的基础知识

1.servlet的工作过程以及容器的作用
Servlet没有main()方法,他们受控与另外一个java应用,这个java应用称为容器(Container)。Tomcat就是这么一个容器,web服务器应用(如Apache)得到一个指向Servlet的请求时,服务器不是把这个请求交给Servlet本身,而是交给部署该servlet的容器。要由容器向servlet提供HTTP请求和响应,而且是由容器调用servlet的方法(doGet()和doPost())。容器运行多个servlet线程来处理对同一servlet的多个请求。(对每个请求分配一个线程,而不是每个客户)
容器的作用:
1)通信支持。利用容器提供的方法,web服务器能轻松的与servlet进行通信。
2)生命周期管理。容器控制着servlet的生与死。它会负责加载类,实例化,初始化,调用servlet的方法以及使servlet能够被垃圾回收。
3)多线程支持。容器会自动的接受每个servlet请求,创建一个新的java线程。针对每个请求,如果servlet已经运行完相应的HTTP方法,线程就会结束。但是我们同时也得考虑线程的安全性。
4)JSP支持。负责将JSP翻译成真正的java。
容器是如何处理用户请求的了?
1)用户点击一个链接,指向一个servlet而不是一个静态页面。
2)web服务器接到这个请求后转发给容器。容器接着创建两个对象:HttpServletRequest和HttpServletResponse。
3)容器根据请求中的URL找到相应的servlet,为这个请求创建一个线程,并把请求对象HtttpServletRequest和响应对象HttpServletResponse传递给这个servlet线程。
4)线程接下来调用service()方法,根据请求的不同,service()方法调用doGet()和doPost()方法。
5)doGet()方法生成动态页面,并把这个页面塞到响应对象里。
6)service()方法结束,随之线程结束,容器把响应对象装换为一个HTTP相应,发送给客户,然后删除请求和响应对象。
2.Servlet的生命周期
注意他的一生都是由容器控制的。servlet一生中只有一个实例出现,但是有多个线程出现。
加载类 Servlet .class文件
实例化 构造函数运行
初始化 容器调用 init() 方法(一生只调一次)
service方法? servlet一生主要在这里度过
销 毁? 销毁实例之前调用 destroy() 方法
可回收? 等待垃圾回收等待垃圾回收
3.Servlet一生中的三大重要时刻
1)init()方法:在servlet实例被创建后调用,可以覆盖此方法做一些初始化的工作,比方说得到一个数据库连接。
2)service()方法:当客户请求到来时,容器会创建一个新的线程,调用servlet的service()方法。servlet的一生基本都在这里度过。我们一般不要覆盖此方法。
3)doGet或者doPost()方法:service方法根据请求的HTTP方法,来调用doGet()或者doPost()方法。我们在开发servlet时肯定要覆盖此方法。每次运行doGet()或者doPost()方法,它都在一个单独的线程
中。
4.容器(tomcat)在启动时会做什么?
容器在启动时,会根据相应的部署文件去寻找servlet文件。
5.为什么要有init方法了?难道不能将init代码放在构造函数中么?
因为让一个普通的java类成为servlet文件时容器付出的代价也挺大,比如说内存分配。在没有调用init方法时他还是一个普普通通的java对象,只有在用户使用时才再让他称为servlet这样对资源的利
用比较合理,注意:init方法是在第一个用户调用此servlet时被触发。













一:Servlet是什么?Servlet容器是什么?Tomcat是什么?Tomcat的组成结构以及Tomcat的工作模式。

最近没事在翻《Tomcat与Java Web开发技术详解》,本文随记一篇。

题外话:前几天做了一幅漫画,发到微博上,效果还不错~




二:Servlet是什么

为了能让Web服务器与Web应用这两个不同的软件系统协作,需要一套标准接口,Servlet就是其中最主要的一个接口。

规定:

Web服务器可以访问任意一个Web应用中实现Servlet接口的类。

Web应用中用于被Web服务器动态调用的程序代码位于Servlet接口的实现类中。

SUN公司(现在被Oracle收购了……)制定了Web应用于Web服务器进行协作的一系列标准Java接口(统称为Java Servlet API)。

SUN公司还对Web服务器发布及运行Web应用的一些细节做了规约。SUN公司把这一系列标准Java接口和规约统称为Servlet规范。

Servlet是一种运行在服务器上的小插件。


Servlet容器是什么

在Servlet规范中,把能够发布和运行JavaWeb应用的Web服务器称为Servlet容器,他的最主要特称是动态执行JavaWeb应用中的Servlet实现类中的程序代码。


Tomcat是什么

Tomcat是Servlet容器,同时也是轻量级的Web服务器。这是它的两个身份!

Apache Server、Microsoft IIS、Apache Tomcat都是Web服务器。

Tomcat作为Web服务器时,主要负责实现HTTP传输等工作。

Tomcat作为Servlet容器时,主要负责解析Request,生成ServletRequest、ServletResponse,将其传给相应的Servlet(调用service( )方法),再将Servlet的相应结果返回。


Tomcat组成结构



Server,代表整个Servlet容器组件,是Tomcat的顶层元素。其中可以包含一到多个Service;

Service,包含一个Engine,以及一到多个Connector;

Connector,代表和客户端程序实际交互的组件,负责接收客户请求,以及向客户返回响应结果;

Engine,处理同一个Service中所有Connector接收到的客户请求;

Host,在Engine中可以包含多个Host,每个Host定义了一个虚拟主机,它可以包含一个到多个Web应用;

Context,一个Host中可以包含多个Context,每个Context代表了运行在虚拟主机上的单个Web应用。

这些字段都在conf/server.xml中配置,下面是一段apache tomcat 6.0.36默认的server.xml:

[html]  view plain  copy
 print ?
  1. <?xml version='1.0' encoding='utf-8'?>  
  2. <!--  
  3.   Licensed to the Apache Software Foundation (ASF) under one or more  
  4.   contributor license agreements.  See the NOTICE file distributed with  
  5.   this work for additional information regarding copyright ownership.  
  6.   The ASF licenses this file to You under the Apache License, Version 2.0  
  7.   (the "License"); you may not use this file except in compliance with  
  8.   the License.  You may obtain a copy of the License at  
  9.   
  10.       http://www.apache.org/licenses/LICENSE-2.0  
  11.   
  12.   Unless required by applicable law or agreed to in writing, software  
  13.   distributed under the License is distributed on an "AS IS" BASIS,  
  14.   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  15.   See the License for the specific language governing permissions and  
  16.   limitations under the License.  
  17. -->  
  18. <!-- Note:  A "Server" is not itself a "Container", so you may not  
  19.      define subcomponents such as "Valves" at this level.  
  20.      Documentation at /docs/config/server.html  
  21.  -->  
  22. <Server port="8005" shutdown="SHUTDOWN">  
  23.   
  24.   <!--APR library loader. Documentation at /docs/apr.html -->  
  25.   <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />  
  26.   <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->  
  27.   <Listener className="org.apache.catalina.core.JasperListener" />  
  28.   <!-- Prevent memory leaks due to use of particular java/javax APIs-->  
  29.   <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />  
  30.   <!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html -->  
  31.   <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />  
  32.   <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />  
  33.   
  34.   <!-- Global JNDI resources  
  35.        Documentation at /docs/jndi-resources-howto.html  
  36.   -->  
  37.   <GlobalNamingResources>  
  38.     <!-- Editable user database that can also be used by  
  39.          UserDatabaseRealm to authenticate users  
  40.     -->  
  41.     <Resource name="UserDatabase" auth="Container"  
  42.               type="org.apache.catalina.UserDatabase"  
  43.               description="User database that can be updated and saved"  
  44.               factory="org.apache.catalina.users.MemoryUserDatabaseFactory"  
  45.               pathname="conf/tomcat-users.xml" />  
  46.   </GlobalNamingResources>  
  47.   
  48.   <!-- A "Service" is a collection of one or more "Connectors" that share  
  49.        a single "Container" Note:  A "Service" is not itself a "Container",   
  50.        so you may not define subcomponents such as "Valves" at this level.  
  51.        Documentation at /docs/config/service.html  
  52.    -->  
  53.   <Service name="Catalina">  
  54.     
  55.     <!--The connectors can use a shared executor, you can define one or more named thread pools-->  
  56.     <!--  
  57.     <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"   
  58.         maxThreads="150" minSpareThreads="4"/>  
  59.     -->  
  60.       
  61.       
  62.     <!-- A "Connector" represents an endpoint by which requests are received  
  63.          and responses are returned. Documentation at :  
  64.          Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)  
  65.          Java AJP  Connector: /docs/config/ajp.html  
  66.          APR (HTTP/AJP) Connector: /docs/apr.html  
  67.          Define a non-SSL HTTP/1.1 Connector on port 8080  
  68.     -->  
  69.     <Connector port="8080" protocol="HTTP/1.1"   
  70.                connectionTimeout="20000"   
  71.                redirectPort="8443" />  
  72.     <!-- A "Connector" using the shared thread pool-->  
  73.     <!--  
  74.     <Connector executor="tomcatThreadPool"  
  75.                port="8080" protocol="HTTP/1.1"   
  76.                connectionTimeout="20000"   
  77.                redirectPort="8443" />  
  78.     -->             
  79.     <!-- Define a SSL HTTP/1.1 Connector on port 8443  
  80.          This connector uses the JSSE configuration, when using APR, the   
  81.          connector should be using the OpenSSL style configuration  
  82.          described in the APR documentation -->  
  83.     <!--  
  84.     <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"  
  85.                maxThreads="150" scheme="https" secure="true"  
  86.                clientAuth="false" sslProtocol="TLS" />  
  87.     -->  
  88.   
  89.     <!-- Define an AJP 1.3 Connector on port 8009 -->  
  90.     <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />  
  91.   
  92.   
  93.     <!-- An Engine represents the entry point (within Catalina) that processes  
  94.          every request.  The Engine implementation for Tomcat stand alone  
  95.          analyzes the HTTP headers included with the request, and passes them  
  96.          on to the appropriate Host (virtual host).  
  97.          Documentation at /docs/config/engine.html -->  
  98.   
  99.     <!-- You should set jvmRoute to support load-balancing via AJP ie :  
  100.     <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">           
  101.     -->   
  102.     <Engine name="Catalina" defaultHost="localhost">  
  103.   
  104.       <!--For clustering, please take a look at documentation at:  
  105.           /docs/cluster-howto.html  (simple how to)  
  106.           /docs/config/cluster.html (reference documentation) -->  
  107.       <!-- 
  108.       <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/> 
  109.       -->          
  110.   
  111.       <!-- The request dumper valve dumps useful debugging information about  
  112.            the request and response data received and sent by Tomcat.  
  113.            Documentation at: /docs/config/valve.html -->  
  114.       <!-- 
  115.       <Valve className="org.apache.catalina.valves.RequestDumperValve"/> 
  116.       -->  
  117.   
  118.       <!-- This Realm uses the UserDatabase configured in the global JNDI  
  119.            resources under the key "UserDatabase".  Any edits  
  120.            that are performed against this UserDatabase are immediately  
  121.            available for use by the Realm.  -->  
  122.       <Realm className="org.apache.catalina.realm.UserDatabaseRealm"  
  123.              resourceName="UserDatabase"/>  
  124.   
  125.       <!-- Define the default virtual host  
  126.            Note: XML Schema validation will not work with Xerces 2.2.  
  127.        -->  
  128.       <Host name="localhost"  appBase="webapps"  
  129.             unpackWARs="true" autoDeploy="true"  
  130.             xmlValidation="false" xmlNamespaceAware="false">  
  131.   
  132.         <!-- SingleSignOn valve, share authentication between web applications  
  133.              Documentation at: /docs/config/valve.html -->  
  134.         <!-- 
  135.         <Valve className="org.apache.catalina.authenticator.SingleSignOn" /> 
  136.         -->  
  137.   
  138.         <!-- Access log processes all example.  
  139.              Documentation at: /docs/config/valve.html -->  
  140.         <!--  
  141.         <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"    
  142.                prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>  
  143.         -->  
  144.   
  145.       </Host>  
  146.     </Engine>  
  147.   </Service>  
  148. </Server>  

Tomcat工作模式

分为三种:

1、独立的Servlet容器

2、其他Web服务器进程内的Servlet容器

3、其他Web服务器进程外的Servlet容器

第一种,Tomcat作为独立的Web服务器单独运行,Servlet容器作为Web服务器的一部分,这也是默认工作模式。

这种模式下,Tomcat是一个独立运行的Java程序,运行在Java虚拟机进程中。



blog:http://blog.youkuaiyun.com/pirateleo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值