簡介
Tomcat啟動時,先找系統變量CATALINA_BASE,如果沒有,則找CATALINA_HOME。然后找這個變量所指的目錄下的conf文件夾,從中讀取配置文件。最重要的配置文件:server.xml 。要配置tomcat,基本上了解server.xml,context.xml和web.xml。
Server.xml -- tomcat主配置文件
Web.xml -- servlet與其他適用於整個Web應用程序設置的配置文件,必須符合servlet規范的標准格式。
Context.xml -- 默認的context配置,應用於安裝了Tomcat的所有主機的所有部署內容。該文件的格式和標准的context XML片段文件的格式完全相同。它應包含在context元素中,而且暗含元素應嵌套與Context中。即該文件中的配置是所有web.xml的全局配置。
applicationContext.xml -- 默認的spring框架全局配置信息
{servlet-name}-servlet.xml -- Spring MVC 的Servlet的核心配置文件
Server.xml
配置元素說明:
| 元素名 |
屬性 |
解釋 |
| server |
port |
指定一個端口,這個端口負責監聽關閉tomcat 的請求 |
| shutdown |
指定向端口發送的命令字符串 |
|
| service |
name |
指定service 的名字 |
| Connector ( 表示客戶端和service之間的連接) |
port |
指定服務器端要創建的端口號,並在這個斷口監聽來自客戶端的請求 |
| minProcessors |
服務器啟動時創建的處理請求的線程數 |
|
| maxProcessors |
最大可以創建的處理請求的線程數 |
|
| enableLookups |
如果為true ,則可以通過調用request.getRemoteHost()進行DNS 查詢來得到遠程客戶端的實際主機名,若為false則不進行DNS 查詢,而是返回其ip 地址 |
|
| redirectPort |
指定服務器正在處理http 請求時收到了一個SSL 傳輸請求后重定向的端口號 |
|
| acceptCount |
指定當所有可以使用的處理請求的線程數都被使用時,可以放到處理隊列中的請求數,超過這個數的請求將不予處理 |
|
| connectionTimeout |
指定超時的時間數( 以毫秒為單位) |
|
| Engine ( 表示指定service 中的請求處理機,接收和處理來自Connector 的請求) |
defaultHost |
指定缺省的處理請求的主機名,它至少與其中的一個host元素的name 屬性值是一樣的 |
| Context ( 表示一個web 應用程序,通常為WAR 文件,關於WAR 的具體信息見servlet 規范) |
docBase |
應用程序的路徑或者是WAR 文件存放的路徑 |
| path |
表示此web 應用程序的url 的前綴,這樣請求的url為http://localhost:8080/path/ **** |
|
| reloadable |
這個屬性非常重要,如果為true ,則tomcat 會自動檢測應用程序的/WEB-INF/lib 和/WEB-INF/classes 目錄的變化,自動裝載新的應用程序,我們可以在不重起tomcat 的情況下改變應用程序 |
|
| host ( 表示一個虛擬主機 ) |
name |
指定主機名 |
| appBase |
應用程序基本目錄,即存放應用程序的目錄 |
|
| unpackWARs |
如果為true ,則tomcat 會自動將WAR 文件解壓,否則不解壓,直接從WAR 文件中運行應用程序 |
|
| Logger ( 表示日志,調試和錯誤信息) |
className |
指定logger 使用的類名,此類必須實現org.apache.catalina.Logger 接口 |
| prefix |
指定log 文件的前綴 |
|
| suffix |
指定log 文件的后綴 |
|
| timestamp |
如果為true ,則log 文件名中要加入時間,如下例:localhost_log.2001-10-04.txt |
|
| Realm ( 表示存放用戶名,密碼及role 的數據庫) |
className |
指定Realm 使用的類名,此類必須實現org.apache.catalina.Realm 接口 |
| Valve ( 功能與Logger 差不多,其prefix和suffix 屬性解釋和Logger 中的一樣) |
className |
指定Valve 使用的類名,如用org.apache.catalina.valves.AccessLogValve 類可以記錄應用程序的訪問信息 |
| directory |
指定log 文件存放的位置 |
|
| pattern |
有兩個值,common 方式記錄遠程主機名或ip 地址,用戶名,日期,第一行請求的字符串,HTTP 響應代碼,發送的字節數。combined 方式比common 方式記錄的值更多 |
<Server>元素
代表整個容器,是Tomcat實例的頂層元素.由org.apache.catalina.Server接口來定義。它包含一個<Service>元素,並且它不能做為任何元素的子元素。
示例:
< Server port ="8005" shutdown ="SHUTDOWN" debug ="0" >
屬性:
1. className指定實現org.apache.catalina.Server接口的類.默認值為
org.apache.catalina.core.StandardServer
2. port指定Tomcat監聽shutdown命令端口.終止服務器運行時,必須在Tomcat服務器所在的機器上發出shutdown命令.該屬性是必須的。
3. shutdown指定終止Tomcat服務器運行時,發給Tomcat服務器的shutdown監聽端口的字符串。該屬性必須設置。
<Service>元素
由org.apache.catalina.Service接口定義,它包含一個<Engine>元素,以及一個或多個
<Connector>,這些Connector元素共享用同一個Engine元素
示例:
< Service name ="Catalina" >
< Service name ="Apache" >
第一個<Service>處理所有直接由Tomcat服務器接收的web客戶請求.
第二個<Service>處理所有由Apahce服務器轉發過來的Web客戶請求
屬性:
1. className 指定實現org.apahce.catalina.Service接口的類.默認為
org.apahce.catalina.core.StandardService
2. name定義Service的名字
<Engine>元素
每個Service元素只能有一個Engine元素,處理在同一個<Service>中所有<Connector>元素接收到的客戶請求。由org.apahce.catalina.Engine接口定義。<Engine>可包含如下元素<Logger>, <Realm>, <Value>, <Host>
示例:
< Engine name ="Catalina" defaultHost ="localhost" debug ="0" >
說明:
1. className指定實現Engine接口的類,默認值為StandardEngine
2. defaultHost指定處理客戶的默認主機名,在<Engine>中的<Host>子元素中必須定義這一主機
3. name定義Engine的名字
<Host>元素
由Host接口定義。一個Engine元素可以包含多個<Host>元素。每個<Host>的元素定義了一個虛擬主機,包含了一個或多個Web應用。<Host>元素中可包含如下子元素<Logger>, <Realm>, <Value>, <Context>
示例:
< Host name ="localhost" debug ="0" appBase ="webapps" unpackWARs ="true" autoDeploy ="true" >
屬性:
1. className指定實現Host接口的類.默認值為StandardHost
2. appBase指定虛擬主機的目錄,可指定絕對目錄,也可指定相對於<CATALINA_HOME>的相對目錄。如果沒有此項,默認為<CATALINA_HOME>/webapps
3. autoDeploy如果此項設為true,表示Tomcat服務處於運行狀態時,能夠監測appBase下的文件,如果有新有web應用加入進來,會自運發布這個WEB應用
4. unpackWARs如果此項設置為true,表示把WEB應用的WAR文件先展開為開放目錄結構后再運行。如果設為false將直接運行為WAR文件
5. alias指定主機別名,可以指定多個別名
6. deployOnStartup如果此項設為true,表示Tomcat服務器啟動時會自動發布appBase目錄下所有的Web應用。如果Web應用中的server.xml沒有相應的<Context>元素,將采用Tomcat默認的Context
7. name定義虛擬主機的名字
<Context>元素
由Context接口定義。是使用最頻繁的元素。每個<Context>元素代表了運行在虛擬主機上的單個Web應用。一個<Host>可以包含多個<Context>元素。每個web應用有唯一的一個相對應的Context代表web應用自身。 servlet容器為第一個web應用創建一個ServletContext對象。<Context>元素可包含如下元素<Logger>, <Realm>, <Resource>, <ResourceParams>
示例:
< Context path ="/sample" docBase ="sample" debug ="0" reloadbale ="true" >
屬性:
1. className指定實現Context的類,默認為StandardContext類
2. path指定訪問Web應用的URL入口,注意/myweb,而不是myweb
3. reloadable如果這個屬性設為true, Tomcat服務器在運行狀態下會監視在WEB-INF/classes和Web-INF/lib目錄CLASS文件的修改,如果監視到有class文件被更新,服務器自重新加載Web應用
4. cookies指定是否通過Cookies來支持Session,默認值為true
5. useNaming指定是否支持JNDI,默認值為了true
<Connector>元素
由Connector接口定義。<Connector>元素代表與客戶程序實際交互的給件,它負責接收客戶請求,以及向客戶返回響應結果.
示例:
< Connector port ="8080" maxThread ="50" minSpareThreads ="25" maxSpareThread ="75"
enableLookups ="false" redirectPort ="8443" acceptCount ="100" debug ="0"
connectionTimeout ="20000" disableUploadTimeout ="true" />
< Connection port ="8009" enableLookups ="false" redirectPort ="8443" debug ="0"
protocol ="AJP/1.3" />
第一個Connector元素定義了一個HTTP Connector,它通過8080端口接收HTTP請求;第二個Connector元素定義了一個JD Connector,它通過8009端口接收由其它服務器轉發過來的請求.
Connector元素共用屬性:
1. className指定實現Connector接口的類
2. enableLookups如果設為true,表示支持域名解析,可以把IP地址解析為主機名.WEB應用中調用request.getRemoteHost方法返回客戶機主機名.默認值為true
3. redirectPort指定轉發端口.如果當前端口只支持non-SSL請求,在需要安全通信的場命,將把客戶請求轉發至SSL的redirectPort端口
HttpConnector元素的屬性
1. className實現Connector的類
2. port設定Tcp/IP端口,默認值為8080,如果把8080改成80,則只要輸入http://localhost 即可,因為TCP/IP的默認端口是80
3. address如果服務器有二個以上ip地址,此屬性可以設定端口監聽的ip地址.默認情況下,端口會監聽服務器上所有的ip地址
4. bufferSize設定由端口創建的輸入流的緩存大小.默認值為2048byte
5. protocol設定Http協議,默認值為HTTP/1.1
6. maxThreads設定在監聽端口的線程的最大數目,這個值也決定了服務器可以同時響應客戶請求的最大數
目.默認值為200
7. acceptCount設定在監聽端口隊列的最大客戶請求數量,默認值為10.如果隊列已滿,客戶必須等待.
8. connectionTimeout定義建立客戶連接超時的時間.如果為-1,表示不限制建立客戶連接的時間
JkConnector的屬性
1. className實現Connector的類
2. port設定AJP端口號
3. protocol必須設定為AJP/1.3
web.xml
Web.xml -- servlet與其他適用於整個Web應用程序設置的配置文件,必須符合servlet規范的標准格式。在Tomcat中,有兩處會用到web.xml: 1) CATALINA_BASE/conf目錄; 2) 每個Web應用程序的./WEB-INF。這兩個文件共同定義Web應該程序的行為。其中CATALINA_BASE/conf/web.xml 是全局配置,適用於所有的Web應用程序。應用程序的./WEB-INF/web.xml 是針對各個Web應該程序的獨立配置,只對單個Web Context有效。一般CATALINA_BASE/conf/web.xml 不需修改,采用Tomcat默認配置即可。
/WEB-INF/web.xml常見配置項
context-param -- 應用於整個Web應用程序(Context)的初始化參數。有多項,則分開。
filter / filter-mapping -- 共同配置Context的過濾規則。filter 配置過濾器;filter-mapping配置過濾規則和過濾器的映射關系。
Listener -- 配置整個Web的事件觸發器。
Servlet / servlet-mapping -- 配置servlet和servlet所處理的HTTP請求(servlet-mapping)
session-config -- 配置HTTP session相關屬性。
welcome-file-list -- 配置歡迎頁。
示例:啟用 Spring 容器和 Spring MVC 框架
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <!-- Spring 服務層的配置文件 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/classes/log4j.properties</param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/application*.xml</param-value> </context-param> <filter> <filter-name>CharacterFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> <init-param> <param-name>force</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring 容器啟動監聽器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring MVC 的Servlet,它將加載WEB-INF/testserver-servlet.xml 的 配置文件,以啟動Spring MVC模塊--> <servlet> <servlet-name>testserver</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>testserver</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <session-config> <!-- Default to 5 minute session timeouts --> <session-timeout>10</session-timeout> </session-config> <welcome-file-list> <welcome-file>/welcome.jsp</welcome-file> </welcome-file-list> </web-app>
tomcat的listener -- servlet容器級(web.xml配置使用)全局事件處理器,繼承自 javax.servlet.ServletContextListener,實現全局數據加載。tomcat服務器啟動時,ServletContextListener 的 contextInitialized()方法被調用,初始化公共的全局數據。在每個servlet context關閉之前,ServletContextListener 的 contextDestroyed()方法被調用,可實現servlet級別的操作,比如關閉超時HTTP鏈接。配置示例:
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>your.ContextListener</listener-class> </listener>
api說明: http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContextListener.html
Web應用程序布局和部署
應用程序布局目錄規范
./webapps/
./webapps/ROOT
./webapps/ROOT/index.html
./webapps/di
./webapps/di/META-INF
./webapps/di/META-INF/MANIFEST.MF
./webapps/di/WEB-INF
./webapps/di/WEB-INF/lib
./webapps/di/WEB-INF/di-servlet.xml
./webapps/di/WEB-INF/applicationContext.xml
./webapps/di/WEB-INF/classes
./webapps/di/WEB-INF/web.xml
其中,web.xml是核心配置文件。
部署
解包目錄的Web部署方式
服務提供者可將相應的class和lib放在相應目錄下。優點:易於診斷故障;支持單jar、class文件更新。缺點:不好監控文件變更。
WAR文件部署方式
Java servlet規范支持將整個Web目錄下的所有文件(配置、class、jar等)打包成WAR文件,以單個WAR文件方式部署Web應用程序。優點:容易監控WAR文件變更,有利於安全防護(防黑客攻擊)。
Spring MVC配置
org.springframework.web.context.ContextLoaderListener
ContextLoaderListener的作用就是啟動Web容器時,自動裝配ApplicationContext的配置信息。因為它實現了ServletContextListener這個接口,在web.xml配置這個監聽器,啟動容器時,就會默認執行它實現的方法。
ApplicationContext.xml這個配置文件部署: 如果在web.xml中不寫任何參數配置信息,默認的路徑是”/WEB-INF/applicationContext.xml,在WEB-INF目錄下創建的xml文件的名稱必須是applicationContext.xml。如果是要自定義文件名可在web.xml里加入contextConfigLocation這個context參數:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/applicationContext-*.xml
</param-value>
</context-param>
在<param-value> </param-value>里指定相應的xml文件名;如果有多個xml文件,可寫在一起並一“,”號分隔。上面的applicationContext-*.xml采用通配符,比如這那個目錄下有applicationContext-ibatis-base.xml,applicationContext-action.xml,applicationContext-ibatis-dao.xml等文件,都會一同被載入。
由此可見applicationContext.xml的文件位置就可以有兩種默認實現:
第一種:直接將之放到/WEB-INF下,並在web.xml中聲明一個listener。
第二種:放到classpath下,且需在web.xml中加入<context-param>,用它來指明你的applicationContext.xml的位置以供web容器來加載。按照 Struts2 整合spring的官方給出的檔案,寫成:
<!-- Context Configuration locations for Spring XML files -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext-*.xml,classpath:applicationContext-*.xml</param-value>
</context-param>
*-servlet.xml 示例(可使用ContextLoaderListener載入的配置)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>/WEB-INF/classes/test.properties</value> </list> </property> </bean> <bean id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/gettest.do">getTestController</prop> </props> </property> </bean> <bean name="getTestController" class="com.test.service.diserviceDo" singleton="false"> <property name="onlineIndex" ref="diIndex" /> <property name="yearIndex" ref="yearIndex" /> </bean> <bean id="diIndex" class="com.di.service.MulSearch" singleton="true"> <constructor-arg value="${di.dir}" /> <constructor-arg value="${di.num}" /> </bean> <bean id="yearIndex" class="com.di.service.MulSearch" singleton="true"> <constructor-arg value="${year.dir}" /> <constructor-arg value="${year.num}" /> </bean> </beans>
Handler Interceptor攔截請求
Spring MVC允許你通過處理攔截攔截web請求,進行前置處理和后置處理。處理攔截是在Spring的web應用程序上下文中配置的,因此它們可以利用各種容器特性,並引用容器中聲明的任何Bean。處理攔截是針對特殊的處理程序映射進行注冊的,因此它只攔截通過這些處理程序映射的請求。每個處理攔截都必須實現HandlerInterceptor接口,它包含三個需要你實現的回調方法:preHandle(),postHandle()和afterCompletion()。第一個和第二個方法分別是在處理程序處理請求之前和之后被調用的。第二個方法還允許訪問返回的ModelAndView對象,因此可以在它里面操作模型屬性。最后一個方法是在所有請求處理完成之后被調用的(如視圖呈現之后)。參見:spring MVC之用Handler Interceptor攔截請求
api說明:
http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/web/servlet/handler/HandlerInterceptorAdapter.html
spring mvc的異常處理機制
spring mvc提供了:
org.springframework.web.servlet.HandlerExceptionResolver
接口用於處理異常,該接口需要開發者實現方法,根據異常類型和上下文數據,返回ModelAndView。見該類的javadoc
簡單使用示例(實現MyExceptionHandleResolver,*-servlet.xml 添加如下配置):
<bean id="myExceptionResolver" class="com.exception.resolver.MyExceptionHandleResolver" />
使用示例:映射錯誤頁面
http://marshal.easymorse.com/archives/1379
偽靜態配置:
web.xml
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
urlrewrite.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 2.6//EN" "http://tuckey.org/res/dtds/urlrewrite2.6.dtd"> <urlrewrite> <rule> <note>新聞</note> <from>^/news/([0-9]+).html$</from> <to>/newview.htm?id=$1</to> </rule> <rule> <note>禮包</note> <from>^/libao/([0-9]+).html$</from> <to>/libaoview.htm?id=$1</to> </rule> <rule> <note>游戲</note> <from>^/youxi/([0-9]+).html$</from> <to>/gameview.htm?gameid=$1</to> </rule> <rule> <note>游戲列表</note> <from>^/games_([0-9]+)_([0-9]+)_([0-9]+).html$</from> <to>/games.htm?type=$1&gametype=$2&page=$3</to> </rule> <rule> <note>資訊列表</note> <from>^/news_([0-9]+)_([0-9]+).html$</from> <to>/news.htm?type=$1&page=$2</to> </rule> <rule> <note>禮包列表</note> <from>^/libaos_([0-9]+).html$</from> <to>/libaos.htm?page=$1</to> </rule> </urlrewrite>
參考文章
Tomcat權威指南 - 第三章、第七章
