在网络上找了许久,没有一个真正可以解决TomCat多虚拟站点的配置问题的,经过试验和参考官方网站资料,终于解决了这个问题.
参考资料:ApacheTomcat文档 http://tomcat.apache.org/tomcat-5.0-doc/config/host.html
在文中有这么一段话:
OneormoreHostelementsarenestedinsideanEngineelement.InsidetheHostelement,youcannest
Contextelementsforthewebapplicationsassociatedwiththisvirtualhost.ExactlyoneoftheHosts
associatedwitheachEngineMUSThaveanamematchingthedefaultHostattributeofthatEngine.
译文:Engine元素中需要一个或多个Host元素,在Host元素里面,你必需有Context元素让网站应用程序与虚拟主机连接上,严密地说,每一个主机所关联的引擎必须有一个名字跟那个引擎默认的主机属性匹配.
可知,在Engine元素里面可以有多个Host,那么说,可以有在一个Engine里面设置多个服务器了,这正是我们需要的.每个Host元素里面要有一个Context元素.
根据conf\server.xml里面的说明和范例,我样可以编写出下面一个配置文件:
1<!--ExampleServerConfigurationFile-->
2<!--Notethatcomponentelementsarenestedcorrespondingtotheir
3parent-childrelationshipswitheachother-->
4
5<!--A"Server"isasingletonelementthatrepresentstheentireJVM,
6whichmaycontainoneormore"Service"instances.TheServer
7listensforashutdowncommandontheindicatedport.
8
9Note:A"Server"isnotitselfa"Container",soyoumaynot
10definesubcomponentssuchas"Valves"or"Loggers"atthislevel.
11-->
12
13<Serverport="8005"shutdown="SHUTDOWN">
14
15<!--CommenttheseentriesouttodisableJMXMBeanssupportusedforthe
16administrationwebapplication-->
17<ListenerclassName="org.apache.catalina.core.AprLifecycleListener"/>
18<ListenerclassName="org.apache.catalina.mbeans.ServerLifecycleListener"/>
19<ListenerclassName="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
20<ListenerclassName="org.apache.catalina.storeconfig.StoreConfigLifecycleListener"/>
21
22<!--GlobalJNDIresources-->
23<GlobalNamingResources>
24
25<!--Testentryfordemonstrationpurposes-->
26<Environmentname="simpleValue"type="java.lang.Integer"value="30"/>
27
28<!--Editableuserdatabasethatcanalsobeusedby
29UserDatabaseRealmtoauthenticateusers-->
30<Resourcename="UserDatabase"auth="Container"
31type="org.apache.catalina.UserDatabase"
32description="Userdatabasethatcanbeupdatedandsaved"
33factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
34pathname="conf/tomcat-users.xml"/>
35
36</GlobalNamingResources>
37
38<!--A"Service"isacollectionofoneormore"Connectors"thatshare
39asingle"Container"(andthereforethewebapplicationsvisible
40withinthatContainer).Normally,thatContainerisan"Engine",
41butthisisnotrequired.
42
43Note:A"Service"isnotitselfa"Container",soyoumaynot
44definesubcomponentssuchas"Valves"or"Loggers"atthislevel.
45-->
46
47<!--DefinetheTomcatStand-AloneService-->
48<Servicename="Catalina">
49
50<!--A"Connector"representsanendpointbywhichrequestsarereceived
51andresponsesarereturned.EachConnectorpassesrequestsontothe
52associated"Container"(normallyanEngine)forprocessing.
53
54Bydefault,anon-SSLHTTP/1.1Connectorisestablishedonport8080.
55YoucanalsoenableanSSLHTTP/1.1Connectoronport8443by
56followingtheinstructionsbelowanduncommentingthesecondConnector
57entry.SSLsupportrequiresthefollowingsteps(seetheSSLConfig
58HOWTOintheTomcat5documentationbundleformoredetailed
59instructions):
60*IfyourJDKversion1.3orprior,downloadandinstallJSSE1.0.2or
61later,andputtheJARfilesinto"$JAVA_HOME/jre/lib/ext".
62*Execute:
63%JAVA_HOME%\bin\keytool-genkey-aliastomcat-keyalgRSA(Windows)
64$JAVA_HOME/bin/keytool-genkey-aliastomcat-keyalgRSA(Unix)
65withapasswordvalueof"changeit"forboththecertificateand
66thekeystoreitself.
67
68Bydefault,DNSlookupsareenabledwhenawebapplicationcalls
69request.getRemoteHost().Thiscanhaveanadverseimpacton
70performance,soyoucandisableitbysettingthe
71"enableLookups"attributeto"false".WhenDNSlookupsaredisabled,
72request.getRemoteHost()willreturntheStringversionofthe
73IPaddressoftheremoteclient.
74-->
75
76<!--Defineanon-SSLHTTP/1.1Connectoronport8080-->
77<Connector
78port="80"maxHttpHeaderSize="8192"
79maxThreads="150"minSpareThreads="25"maxSpareThreads="75"
80enableLookups="false"redirectPort="8443"acceptCount="100"
81connectionTimeout="20000"disableUploadTimeout="true"URIEncoding="GB2312"/>
82<!--Note:Todisableconnectiontimeouts,setconnectionTimeoutvalue
83to0-->
84
85<!--Note:Tousegzipcompressionyoucouldsetthefollowingproperties:
86
87compression="on"
88compressionMinSize="2048"
89noCompressionUserAgents="gozilla,traviata"
90compressableMimeType="text/html,text/xml"
91-->
92
93<!--DefineaSSLHTTP/1.1Connectoronport8443-->
94<!--
95<Connectorport="8443"maxHttpHeaderSize="8192"
96maxThreads="150"minSpareThreads="25"maxSpareThreads="75"
97enableLookups="false"disableUploadTimeout="true"
98acceptCount="100"scheme="https"secure="true"
99clientAuth="false"sslProtocol="TLS"/>
100-->
101
102<!--DefineanAJP1.3Connectoronport8009-->
103<Connectorport="8009"
104enableLookups="false"redirectPort="8443"protocol="AJP/1.3"/>
105
106<!--DefineaProxiedHTTP/1.1Connectoronport8082-->
107<!--Seeproxydocumentationformoreinformationaboutusingthis.-->
108<!--
109<Connectorport="8082"
110maxThreads="150"minSpareThreads="25"maxSpareThreads="75"
111enableLookups="false"acceptCount="100"connectionTimeout="20000"
112proxyPort="80"disableUploadTimeout="true"/>
113-->
114
115<!--AnEnginerepresentstheentrypoint(withinCatalina)thatprocesses
116everyrequest.TheEngineimplementationforTomcatstandalone
117analyzestheHTTPheadersincludedwiththerequest,andpassesthem
118ontotheappropriateHost(virtualhost).-->
119
120<!--YoushouldsetjvmRoutetosupportload-balancingviaAJPie:
121<Enginename="Standalone"defaultHost="localhost"jvmRoute="jvm1">
122-->
123
124<!--Definethetoplevelcontainerinourcontainerhierarchy-->
125<Enginename="Catalina"defaultHost="ycoe.vicp.net">
126
127<!--Therequestdumpervalvedumpsusefuldebugginginformationabout
128therequestheadersandcookiesthatwerereceived,andtheresponse
129headersandcookiesthatweresent,forallrequestsreceivedby
130thisinstanceofTomcat.Ifyoucareonlyaboutrequeststoa
131particularvirtualhost,oraparticularapplication,nestthis
132elementinsidethecorresponding<Host>or<Context>entryinstead.
133
134ForasimilarmechanismthatisportabletoallServlet2.4
135containers,checkoutthe"RequestDumperFilter"Filterinthe
136exampleapplication(thesourceforthisfiltermaybefoundin
137"$CATALINA_HOME/webapps/examples/WEB-INF/classes/filters").
138
139Requestdumpingisdisabledbydefault.Uncommentthefollowing
140elementtoenableit.-->
141<!--
142<ValveclassName="org.apache.catalina.valves.RequestDumperValve"/>
143-->
144
145<!--BecausethisRealmishere,aninstancewillbesharedglobally-->
146
147<!--ThisRealmusestheUserDatabaseconfiguredintheglobalJNDI
148resourcesunderthekey"UserDatabase".Anyedits
149thatareperformedagainstthisUserDatabaseareimmediately
150availableforusebytheRealm.-->
151<RealmclassName="org.apache.catalina.realm.UserDatabaseRealm"
152resourceName="UserDatabase"/>
153
154<!--Commentouttheoldrealmbutleaveherefornowincasewe
155needtogobackquickly-->
156<!--
157<RealmclassName="org.apache.catalina.realm.MemoryRealm"/>
158-->
159
160<!--ReplacetheaboveRealmwithoneofthefollowingtogetaRealm
161storedinadatabaseandaccessedviaJDBC-->
162
163<!--
164<RealmclassName="org.apache.catalina.realm.JDBCRealm"
165driverName="org.gjt.mm.mysql.Driver"
166connectionURL="jdbc:mysql://localhost/authority"
167connectionName="test"connectionPassword="test"
168userTable="users"userNameCol="user_name"userCredCol="user_pass"
169userRoleTable="user_roles"roleNameCol="role_name"/>
170-->
171
172<!--
173<RealmclassName="org.apache.catalina.realm.JDBCRealm"
174driverName="oracle.jdbc.driver.OracleDriver"
175connectionURL="jdbc:oracle:thin:@ntserver:1521:ORCL"
176connectionName="scott"connectionPassword="tiger"
177userTable="users"userNameCol="user_name"userCredCol="user_pass"
178userRoleTable="user_roles"roleNameCol="role_name"/>
179-->
180
181<!--
182<RealmclassName="org.apache.catalina.realm.JDBCRealm"
183driverName="sun.jdbc.odbc.JdbcOdbcDriver"
184connectionURL="jdbc:odbc:CATALINA"
185userTable="users"userNameCol="user_name"userCredCol="user_pass"
186userRoleTable="user_roles"roleNameCol="role_name"/>
187-->
188
189<!--Definethedefaultvirtualhost
190Note:XMLSchemavalidationwillnotworkwithXerces2.2.
191-->
192<Hostname="ycoe.vicp.net"appBase="webapps"
193unpackWARs="true"autoDeploy="true"
194xmlValidation="false"xmlNamespaceAware="false">
195
196<!--Definesaclusterforthisnode,
197Bydefiningthiselement,meansthateverymanagerwillbechanged.
198Sowhenrunningacluster,onlymakesurethatyouhavewebappsinthere
199thatneedtobeclusteredandremovetheotherones.
200Aclusterhasthefollowingparameters:
201
202className=thefullyqualifiednameoftheclusterclass
203
204name=adescriptivenameforyourcluster,canbeanything
205
206mcastAddr=themulticastaddress,hastobethesameforallthenodes
207
208mcastPort=themulticastport,hastobethesameforallthenodes
209
210mcastBindAddr=bindthemulticastsockettoaspecificaddress
211
212mcastTTL=themulticastTTLifyouwanttolimityourbroadcast
213
214mcastSoTimeout=themulticastreadtimeout
215
216mcastFrequency=thenumberofmillisecondsinbetweensendinga"I'malive"heartbeat
217
218mcastDropTime=thenumberamillisecondsbeforeanodeisconsidered"dead"ifnoheartbeatisreceived
219
220tcpThreadCount=thenumberofthreadstohandleincomingreplicationrequests,optimalwouldbethesame
amountofthreadsasnodes
221
222tcpListenAddress=thelistenaddress(bindaddress)forTCPclusterrequestonthishost,
223incaseofmultipleethernetcards.
224automeansthataddressbecomes
225InetAddress.getLocalHost().getHostAddress()
226
227tcpListenPort=thetcplistenport
228
229tcpSelectorTimeout=thetimeout(ms)fortheSelector.select()methodincasetheOS
230hasawakupbuginjava.nio.Setto0fornotimeout
231
232printToScreen=truemeansthatmanagerswillalsoprinttostd.out
233
234expireSessionsOnShutdown=truemeansthat
235
236useDirtyFlag=truemeansthatweonlyreplicateasessionaftersetAttribute,removeAttributehasbeencalled.
237falsemeanstoreplicatethesessionaftereachrequest.
238falsemeansthatreplicationwouldworkforthefollowingpieceofcode:(onlyforSimpleTcpReplicationManager)
239<%
240HashMapmap=(HashMap)session.getAttribute("map");
241map.put("key","value");
242%>
243replicationMode=canbeeither'pooled','synchronous'or'asynchronous'.
244*Pooledmeansthatthereplicationhappensusingseveralsocketsinasynchronousway.Ie,
thedatagetsreplicated,thentherequestreturn.Thisisthesameasthe'synchronous'settingexceptitusesapoolofsockets,
henceitismultithreaded.Thisisthefastestandsafestconfiguration.Tousethis,alsoincreasethenroftcpthreads
thatyouhavedealingwithreplication.
245*Synchronousmeansthatthethreadthatexecutestherequest,isalsothe
246threadthereplicatesthedatatotheothernodes,andwillnotreturnuntilall
247nodeshavereceivedtheinformation.
248*Asynchronousmeansthatthereisaspecific'sender'threadforeachclusternode,
249sotherequestthreadwillqueuethereplicationrequestintoa"smart"queue,
250andthenreturntotheclient.
251The"smart"queueisaqueuewherewhenasessionisaddedtothequeue,andthesamesession
252alreadyexistsinthequeuefromapreviousrequest,thatsessionwillbereplaced
253inthequeueinsteadofreplicatingtworequests.Thisalmostneverhappens,unlessthereisa
254largenetworkdelay.
255-->
256<!--
257Whenconfiguringforclustering,youalsoaddinavalvetocatchalltherequests
258comingin,attheendoftherequest,thesessionmayormaynotbereplicated.
259Asessionisreplicatedifandonlyifalltheconditionsaremet:
2601.useDirtyFlagistrueorsetAttributeorremoveAttributehasbeencalledAND
2612.asessionexists(hasbeencreated)
2623.therequestisnottrappedbythe"filter"attribute
263
264Thefilterattributeistofilteroutrequeststhatcouldnotmodifythesession,
265hencewedon'treplicatethesessionaftertheendofthisrequest.
266Thefilterisnegative,ie,anythingyouputinthefilter,youmeantofilterout,
267ie,noreplicationwillbedoneonrequeststhatmatchoneofthefilters.
268Thefilterattributeisdelimitedby;,soyoucan'tescapeout;evenifyouwantedto.
269
270filter=".*\.gif;.*\.js;"meansthatwewillnotreplicatethesessionafterrequestswiththeURI
271endingwith.gifand.jsareintercepted.
272
273Thedeployerelementcanbeusedtodeployappsclusterwide.
274Currentlythedeploymentonlydeploys/undeploystoworkingmembersinthecluster
275sonoWARsarecopieduponsstartupofabrokennode.
276Thedeployerwatchesadirectory(watchDir)forWARfileswhenwatchEnabled="true"
277Whenanewwarfileisaddedthewargetsdeployedtothelocalinstance,
278andthendeployedtotheotherinstancesinthecluster.
279WhenawarfileisdeletedfromthewatchDirthewarisundeployedlocally
280andclusterwide
281-->
282
283<!--
284<ClusterclassName="org.apache.catalina.cluster.tcp.SimpleTcpCluster"
285managerClassName="org.apache.catalina.cluster.session.DeltaManager"
286expireSessionsOnShutdown="false"
287useDirtyFlag="true"
288notifyListenersOnReplication="true">
289
290<Membership
291className="org.apache.catalina.cluster.mcast.McastService"
292mcastAddr="228.0.0.4"
293mcastPort="45564"
294mcastFrequency="500"
295mcastDropTime="3000"/>
296
297<Receiver
298className="org.apache.catalina.cluster.tcp.ReplicationListener"
299tcpListenAddress="auto"
300tcpListenPort="4001"
301tcpSelectorTimeout="100"
302tcpThreadCount="6"/>
303
304<Sender
305className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
306replicationMode="pooled"
307ackTimeout="15000"/>
308
309<ValveclassName="org.apache.catalina.cluster.tcp.ReplicationValve"
310filter=".*\.gif;.*\.js;.*\.jpg;.*\.htm;.*\.html;.*\.txt;"/>
311
312<DeployerclassName="org.apache.catalina.cluster.deploy.FarmWarDeployer"
313tempDir="/tmp/war-temp/"
314deployDir="/tmp/war-deploy/"
315watchDir="/tmp/war-listen/"
316watchEnabled="false"/>
317</Cluster>
318-->
319
320
321
322<!--Normally,usersmustauthenticatethemselvestoeachwebapp
323individually.Uncommentthefollowingentryifyouwouldlike
324ausertobeauthenticatedthefirsttimetheyencountera
325resourceprotectedbyasecurityconstraint,andthenhavethat
326useridentitymaintainedacross*all*webapplicationscontained
327inthisvirtualhost.-->
328<!--
329<ValveclassName="org.apache.catalina.authenticator.SingleSignOn"/>
330-->
331
332<!--Accesslogprocessesallrequestsforthisvirtualhost.By
333default,logfilesarecreatedinthe"logs"directoryrelativeto
334$CATALINA_HOME.Ifyouwish,youcanspecifyadifferent
335directorywiththe"directory"attribute.Specifyeitherarelative
336(to$CATALINA_HOME)orabsolutepathtothedesireddirectory.
337-->
338<!--
339<ValveclassName="org.apache.catalina.valves.AccessLogValve"
340directory="logs"prefix="localhost_access_log."suffix=".txt"
341pattern="common"resolveHosts="false"/>
342-->
343
344<!--Accesslogprocessesallrequestsforthisvirtualhost.By
345default,logfilesarecreatedinthe"logs"directoryrelativeto
346$CATALINA_HOME.Ifyouwish,youcanspecifyadifferent
347directorywiththe"directory"attribute.Specifyeitherarelative
348(to$CATALINA_HOME)orabsolutepathtothedesireddirectory.
349Thisaccesslogimplementationisoptimizedformaximumperformance,
350butishardcodedtosupportonlythe"common"and"combined"patterns.
351-->
352<!--
353<ValveclassName="org.apache.catalina.valves.FastCommonAccessLogValve"
354directory="logs"prefix="localhost_access_log."suffix=".txt"
355pattern="common"resolveHosts="false"/>
356-->
357<ContextdocBase="D:\WORKS\EShop\EWebShop"path="/"reloadable="true"
workDir="D:\WORKS\EShop\Tomcat\work\EWebShop">
358</Context>
359</Host>
360<Hostname="yvor.vicp.net"appBase="webapps"unpackWARs="true"autoDeploy="true"xmlValidation="false"
xmlNamespaceAware="false">
361<ContextdocBase="D:\WORKS\YCOE\ycoe"path="/"reloadable="true"workDir="D:\WORKS\YCOE\Tomcat\work\ycoe">
362</Context>
363</Host>
364</Engine>
365</Service>
366</Server>
367
368
可以看到,这里修改了
81行修改了两个参数值:<Connectorport="80"maxHttpHeaderSize="8192"
maxThreads="150"minSpareThreads="25"maxSpareThreads="75"
enableLookups="false"redirectPort="8443"acceptCount="100"
connectionTimeout="20000"disableUploadTimeout="true"URIEncoding="GB2312"/>
修改port是修改Tomcat的服务端口,默认为8080,URIEncoding改为GB2312是为了使用中文路径
但不建议使用.
125行:<Enginename="Catalina"defaultHost="ycoe.vicp.net">
192行:<Hostname="ycoe.vicp.net"appBase="webapps"unpackWARs="true"autoDeploy="true"xmlValidation="false"xmlNamespaceAware="false">
然后再添加360行开始的<Host>元素:<Hostname="yvor.vicp.net"appBase="webapps"unpackWARs="true"autoDeploy="true"
xmlValidation="false"xmlNamespaceAware="false">
<ContextdocBase="D:\WORKS\YCOE\ycoe"path="/"reloadable="true"
workDir="D:\WORKS\YCOE\Tomcat\work\ycoe"></Context>
</Host>
这里是设置我们的第二个虚拟网站的域名.
注:<Context/>里面的内容并不是我们实际应用的,我们可以通过另一种比较方便而且容易修改的方式来设置这些参数.下面我们来做这方面的配置:
1.在%CATALINA_HOME%\conf\Catalina目录下创建ycoe.vicp.net和yvor.vicp.net两个文件夹.
2.在这两个文件夹里面创建ROOT.xml文件(要以ROOT.xml为名称,否则虽然不会出错,但不能用http://ycoe.vicp.net或http://yvor.vicp.net直接访问)
3.ROOT.xml的内容如下:
<?xmlversion='1.0'encoding='utf-8'?>
<ContextdocBase="D:\WORKS\EShop\EWebShop"path="/"reloadable="true"
workDir="D:\WORKS\EShop\Tomcat\work\EWebShop">
</Context>
根据自己的实际情况,设置这里的docBase和workDir的路径.docBase是说明文档的路径,
workDir是网站程序的路径,如果用相对路径,则是在%CATALINA_HOME%\webapp目录下,path是访问的路径
参考官方文档:
AnyXMLfileinthe$CATALINA_HOME/conf/[engine_name]/[host_name]directoryisassumedtocontainaContextelement(anditsassociatedsubelements)
forasinglewebapplication.ThedocBaseattributeofthis<Context>elementwilltypicallybetheabsolute
pathnametoawebapplicationdirectory,ortheabsolutepathnameofawebapplicationarchive(WAR)
file(whichwillnotbeexpanded).
Anywebapplicationarchivefilewithintheapplicationbase(appBase)directorythatdoesnothavea
correspondingdirectoryofthesamename(withoutthe".war"extension)willbeautomaticallyexpanded,
unlesstheunpackWARspropertyissettofalse.IfyouredeployanupdatedWARfile,besuretodeletethe
expandeddirectorywhenrestartingTomcat,sothattheupdatedWARfilewillbere-expanded(notethattheautodeployerwillautomaticallytakecareofthisifitisenabled).
Anysubdirectorywithintheapplicationbasedirectorythatappearstobeanunpackedwebapplication
(thatis,itcontainsa/WEB-INF/web.xmlfile)willreceiveanautomaticallygeneratedContextelement,evenifthisdirectoryisnot
mentionedintheconf/server.xmlfile.ThisgeneratedContextentrywillbeconfiguredaccordingtothe
propertiessetinanyDefaultContextelementnestedinthisHostelement.Thecontextpathforthis
deployedContextwillbeaslashcharacter("/")followedbythedirectoryname,unlessthedirectorynameis
ROOT,inwhichcasethecontextpathwillbeanemptystring("").
你也可以在这两个目录下创建其它xml的文件
但是这时你通过浏览器访问http://ycoe.vicp.net或http://yvor.vicp.net时并不能浏览到你的网页,因为它把这些网址解析到广域网上去了,除非你用域名绑定.
为了让局域本机不把这两个网址解析到广域网上去.我们可以通过以下设置实现(WindowsXP,其它操作系统没有试过):
1.用文本编辑器打开C:\WINDOWS\system32\drivers\etc目录的hosts文件
2.在内容最后另起一行,添加以下内容:
127.0.0.1ycoe.vicp.net
127.0.0.1yvor.vicp.net
可以由上面的注释部分了解它的作用:
#Copyright(c)1993-1999MicrosoftCorp.
#
#ThisisasampleHOSTSfileusedbyMicrosoftTCP/IPforWindows.
#
#ThisfilecontainsthemappingsofIPaddressestohostnames.Each
#entryshouldbekeptonanindividualline.TheIPaddressshould
#beplacedinthefirstcolumnfollowedbythecorrespondinghostname.
#TheIPaddressandthehostnameshouldbeseparatedbyatleastone
#space.
#
#Additionally,comments(suchasthese)maybeinsertedonindividual
#linesorfollowingthemachinenamedenotedbya'#'symbol.
#
#Forexample:
#
#102.54.94.97rhino.acme.com#sourceserver
#38.25.63.10x.acme.com#xclienthost
到这里,全部的配置已经完成了.重启Tomcat,打开http://ycoe.vicp.net或http://yvor.vicp.net就可以看到预期的效果了.呵呵
下载相关文件 http://www.cnblogs.com/Files/ycoe/Catalina.rar
参考资料:ApacheTomcat文档 http://tomcat.apache.org/tomcat-5.0-doc/config/host.html
在文中有这么一段话:
OneormoreHostelementsarenestedinsideanEngineelement.InsidetheHostelement,youcannest
Contextelementsforthewebapplicationsassociatedwiththisvirtualhost.ExactlyoneoftheHosts
associatedwitheachEngineMUSThaveanamematchingthedefaultHostattributeofthatEngine.
译文:Engine元素中需要一个或多个Host元素,在Host元素里面,你必需有Context元素让网站应用程序与虚拟主机连接上,严密地说,每一个主机所关联的引擎必须有一个名字跟那个引擎默认的主机属性匹配.
可知,在Engine元素里面可以有多个Host,那么说,可以有在一个Engine里面设置多个服务器了,这正是我们需要的.每个Host元素里面要有一个Context元素.
根据conf\server.xml里面的说明和范例,我样可以编写出下面一个配置文件:
1<!--ExampleServerConfigurationFile-->
2<!--Notethatcomponentelementsarenestedcorrespondingtotheir
3parent-childrelationshipswitheachother-->
4
5<!--A"Server"isasingletonelementthatrepresentstheentireJVM,
6whichmaycontainoneormore"Service"instances.TheServer
7listensforashutdowncommandontheindicatedport.
8
9Note:A"Server"isnotitselfa"Container",soyoumaynot
10definesubcomponentssuchas"Valves"or"Loggers"atthislevel.
11-->
12
13<Serverport="8005"shutdown="SHUTDOWN">
14
15<!--CommenttheseentriesouttodisableJMXMBeanssupportusedforthe
16administrationwebapplication-->
17<ListenerclassName="org.apache.catalina.core.AprLifecycleListener"/>
18<ListenerclassName="org.apache.catalina.mbeans.ServerLifecycleListener"/>
19<ListenerclassName="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
20<ListenerclassName="org.apache.catalina.storeconfig.StoreConfigLifecycleListener"/>
21
22<!--GlobalJNDIresources-->
23<GlobalNamingResources>
24
25<!--Testentryfordemonstrationpurposes-->
26<Environmentname="simpleValue"type="java.lang.Integer"value="30"/>
27
28<!--Editableuserdatabasethatcanalsobeusedby
29UserDatabaseRealmtoauthenticateusers-->
30<Resourcename="UserDatabase"auth="Container"
31type="org.apache.catalina.UserDatabase"
32description="Userdatabasethatcanbeupdatedandsaved"
33factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
34pathname="conf/tomcat-users.xml"/>
35
36</GlobalNamingResources>
37
38<!--A"Service"isacollectionofoneormore"Connectors"thatshare
39asingle"Container"(andthereforethewebapplicationsvisible
40withinthatContainer).Normally,thatContainerisan"Engine",
41butthisisnotrequired.
42
43Note:A"Service"isnotitselfa"Container",soyoumaynot
44definesubcomponentssuchas"Valves"or"Loggers"atthislevel.
45-->
46
47<!--DefinetheTomcatStand-AloneService-->
48<Servicename="Catalina">
49
50<!--A"Connector"representsanendpointbywhichrequestsarereceived
51andresponsesarereturned.EachConnectorpassesrequestsontothe
52associated"Container"(normallyanEngine)forprocessing.
53
54Bydefault,anon-SSLHTTP/1.1Connectorisestablishedonport8080.
55YoucanalsoenableanSSLHTTP/1.1Connectoronport8443by
56followingtheinstructionsbelowanduncommentingthesecondConnector
57entry.SSLsupportrequiresthefollowingsteps(seetheSSLConfig
58HOWTOintheTomcat5documentationbundleformoredetailed
59instructions):
60*IfyourJDKversion1.3orprior,downloadandinstallJSSE1.0.2or
61later,andputtheJARfilesinto"$JAVA_HOME/jre/lib/ext".
62*Execute:
63%JAVA_HOME%\bin\keytool-genkey-aliastomcat-keyalgRSA(Windows)
64$JAVA_HOME/bin/keytool-genkey-aliastomcat-keyalgRSA(Unix)
65withapasswordvalueof"changeit"forboththecertificateand
66thekeystoreitself.
67
68Bydefault,DNSlookupsareenabledwhenawebapplicationcalls
69request.getRemoteHost().Thiscanhaveanadverseimpacton
70performance,soyoucandisableitbysettingthe
71"enableLookups"attributeto"false".WhenDNSlookupsaredisabled,
72request.getRemoteHost()willreturntheStringversionofthe
73IPaddressoftheremoteclient.
74-->
75
76<!--Defineanon-SSLHTTP/1.1Connectoronport8080-->
77<Connector
78port="80"maxHttpHeaderSize="8192"
79maxThreads="150"minSpareThreads="25"maxSpareThreads="75"
80enableLookups="false"redirectPort="8443"acceptCount="100"
81connectionTimeout="20000"disableUploadTimeout="true"URIEncoding="GB2312"/>
82<!--Note:Todisableconnectiontimeouts,setconnectionTimeoutvalue
83to0-->
84
85<!--Note:Tousegzipcompressionyoucouldsetthefollowingproperties:
86
87compression="on"
88compressionMinSize="2048"
89noCompressionUserAgents="gozilla,traviata"
90compressableMimeType="text/html,text/xml"
91-->
92
93<!--DefineaSSLHTTP/1.1Connectoronport8443-->
94<!--
95<Connectorport="8443"maxHttpHeaderSize="8192"
96maxThreads="150"minSpareThreads="25"maxSpareThreads="75"
97enableLookups="false"disableUploadTimeout="true"
98acceptCount="100"scheme="https"secure="true"
99clientAuth="false"sslProtocol="TLS"/>
100-->
101
102<!--DefineanAJP1.3Connectoronport8009-->
103<Connectorport="8009"
104enableLookups="false"redirectPort="8443"protocol="AJP/1.3"/>
105
106<!--DefineaProxiedHTTP/1.1Connectoronport8082-->
107<!--Seeproxydocumentationformoreinformationaboutusingthis.-->
108<!--
109<Connectorport="8082"
110maxThreads="150"minSpareThreads="25"maxSpareThreads="75"
111enableLookups="false"acceptCount="100"connectionTimeout="20000"
112proxyPort="80"disableUploadTimeout="true"/>
113-->
114
115<!--AnEnginerepresentstheentrypoint(withinCatalina)thatprocesses
116everyrequest.TheEngineimplementationforTomcatstandalone
117analyzestheHTTPheadersincludedwiththerequest,andpassesthem
118ontotheappropriateHost(virtualhost).-->
119
120<!--YoushouldsetjvmRoutetosupportload-balancingviaAJPie:
121<Enginename="Standalone"defaultHost="localhost"jvmRoute="jvm1">
122-->
123
124<!--Definethetoplevelcontainerinourcontainerhierarchy-->
125<Enginename="Catalina"defaultHost="ycoe.vicp.net">
126
127<!--Therequestdumpervalvedumpsusefuldebugginginformationabout
128therequestheadersandcookiesthatwerereceived,andtheresponse
129headersandcookiesthatweresent,forallrequestsreceivedby
130thisinstanceofTomcat.Ifyoucareonlyaboutrequeststoa
131particularvirtualhost,oraparticularapplication,nestthis
132elementinsidethecorresponding<Host>or<Context>entryinstead.
133
134ForasimilarmechanismthatisportabletoallServlet2.4
135containers,checkoutthe"RequestDumperFilter"Filterinthe
136exampleapplication(thesourceforthisfiltermaybefoundin
137"$CATALINA_HOME/webapps/examples/WEB-INF/classes/filters").
138
139Requestdumpingisdisabledbydefault.Uncommentthefollowing
140elementtoenableit.-->
141<!--
142<ValveclassName="org.apache.catalina.valves.RequestDumperValve"/>
143-->
144
145<!--BecausethisRealmishere,aninstancewillbesharedglobally-->
146
147<!--ThisRealmusestheUserDatabaseconfiguredintheglobalJNDI
148resourcesunderthekey"UserDatabase".Anyedits
149thatareperformedagainstthisUserDatabaseareimmediately
150availableforusebytheRealm.-->
151<RealmclassName="org.apache.catalina.realm.UserDatabaseRealm"
152resourceName="UserDatabase"/>
153
154<!--Commentouttheoldrealmbutleaveherefornowincasewe
155needtogobackquickly-->
156<!--
157<RealmclassName="org.apache.catalina.realm.MemoryRealm"/>
158-->
159
160<!--ReplacetheaboveRealmwithoneofthefollowingtogetaRealm
161storedinadatabaseandaccessedviaJDBC-->
162
163<!--
164<RealmclassName="org.apache.catalina.realm.JDBCRealm"
165driverName="org.gjt.mm.mysql.Driver"
166connectionURL="jdbc:mysql://localhost/authority"
167connectionName="test"connectionPassword="test"
168userTable="users"userNameCol="user_name"userCredCol="user_pass"
169userRoleTable="user_roles"roleNameCol="role_name"/>
170-->
171
172<!--
173<RealmclassName="org.apache.catalina.realm.JDBCRealm"
174driverName="oracle.jdbc.driver.OracleDriver"
175connectionURL="jdbc:oracle:thin:@ntserver:1521:ORCL"
176connectionName="scott"connectionPassword="tiger"
177userTable="users"userNameCol="user_name"userCredCol="user_pass"
178userRoleTable="user_roles"roleNameCol="role_name"/>
179-->
180
181<!--
182<RealmclassName="org.apache.catalina.realm.JDBCRealm"
183driverName="sun.jdbc.odbc.JdbcOdbcDriver"
184connectionURL="jdbc:odbc:CATALINA"
185userTable="users"userNameCol="user_name"userCredCol="user_pass"
186userRoleTable="user_roles"roleNameCol="role_name"/>
187-->
188
189<!--Definethedefaultvirtualhost
190Note:XMLSchemavalidationwillnotworkwithXerces2.2.
191-->
192<Hostname="ycoe.vicp.net"appBase="webapps"
193unpackWARs="true"autoDeploy="true"
194xmlValidation="false"xmlNamespaceAware="false">
195
196<!--Definesaclusterforthisnode,
197Bydefiningthiselement,meansthateverymanagerwillbechanged.
198Sowhenrunningacluster,onlymakesurethatyouhavewebappsinthere
199thatneedtobeclusteredandremovetheotherones.
200Aclusterhasthefollowingparameters:
201
202className=thefullyqualifiednameoftheclusterclass
203
204name=adescriptivenameforyourcluster,canbeanything
205
206mcastAddr=themulticastaddress,hastobethesameforallthenodes
207
208mcastPort=themulticastport,hastobethesameforallthenodes
209
210mcastBindAddr=bindthemulticastsockettoaspecificaddress
211
212mcastTTL=themulticastTTLifyouwanttolimityourbroadcast
213
214mcastSoTimeout=themulticastreadtimeout
215
216mcastFrequency=thenumberofmillisecondsinbetweensendinga"I'malive"heartbeat
217
218mcastDropTime=thenumberamillisecondsbeforeanodeisconsidered"dead"ifnoheartbeatisreceived
219
220tcpThreadCount=thenumberofthreadstohandleincomingreplicationrequests,optimalwouldbethesame
amountofthreadsasnodes
221
222tcpListenAddress=thelistenaddress(bindaddress)forTCPclusterrequestonthishost,
223incaseofmultipleethernetcards.
224automeansthataddressbecomes
225InetAddress.getLocalHost().getHostAddress()
226
227tcpListenPort=thetcplistenport
228
229tcpSelectorTimeout=thetimeout(ms)fortheSelector.select()methodincasetheOS
230hasawakupbuginjava.nio.Setto0fornotimeout
231
232printToScreen=truemeansthatmanagerswillalsoprinttostd.out
233
234expireSessionsOnShutdown=truemeansthat
235
236useDirtyFlag=truemeansthatweonlyreplicateasessionaftersetAttribute,removeAttributehasbeencalled.
237falsemeanstoreplicatethesessionaftereachrequest.
238falsemeansthatreplicationwouldworkforthefollowingpieceofcode:(onlyforSimpleTcpReplicationManager)
239<%
240HashMapmap=(HashMap)session.getAttribute("map");
241map.put("key","value");
242%>
243replicationMode=canbeeither'pooled','synchronous'or'asynchronous'.
244*Pooledmeansthatthereplicationhappensusingseveralsocketsinasynchronousway.Ie,
thedatagetsreplicated,thentherequestreturn.Thisisthesameasthe'synchronous'settingexceptitusesapoolofsockets,
henceitismultithreaded.Thisisthefastestandsafestconfiguration.Tousethis,alsoincreasethenroftcpthreads
thatyouhavedealingwithreplication.
245*Synchronousmeansthatthethreadthatexecutestherequest,isalsothe
246threadthereplicatesthedatatotheothernodes,andwillnotreturnuntilall
247nodeshavereceivedtheinformation.
248*Asynchronousmeansthatthereisaspecific'sender'threadforeachclusternode,
249sotherequestthreadwillqueuethereplicationrequestintoa"smart"queue,
250andthenreturntotheclient.
251The"smart"queueisaqueuewherewhenasessionisaddedtothequeue,andthesamesession
252alreadyexistsinthequeuefromapreviousrequest,thatsessionwillbereplaced
253inthequeueinsteadofreplicatingtworequests.Thisalmostneverhappens,unlessthereisa
254largenetworkdelay.
255-->
256<!--
257Whenconfiguringforclustering,youalsoaddinavalvetocatchalltherequests
258comingin,attheendoftherequest,thesessionmayormaynotbereplicated.
259Asessionisreplicatedifandonlyifalltheconditionsaremet:
2601.useDirtyFlagistrueorsetAttributeorremoveAttributehasbeencalledAND
2612.asessionexists(hasbeencreated)
2623.therequestisnottrappedbythe"filter"attribute
263
264Thefilterattributeistofilteroutrequeststhatcouldnotmodifythesession,
265hencewedon'treplicatethesessionaftertheendofthisrequest.
266Thefilterisnegative,ie,anythingyouputinthefilter,youmeantofilterout,
267ie,noreplicationwillbedoneonrequeststhatmatchoneofthefilters.
268Thefilterattributeisdelimitedby;,soyoucan'tescapeout;evenifyouwantedto.
269
270filter=".*\.gif;.*\.js;"meansthatwewillnotreplicatethesessionafterrequestswiththeURI
271endingwith.gifand.jsareintercepted.
272
273Thedeployerelementcanbeusedtodeployappsclusterwide.
274Currentlythedeploymentonlydeploys/undeploystoworkingmembersinthecluster
275sonoWARsarecopieduponsstartupofabrokennode.
276Thedeployerwatchesadirectory(watchDir)forWARfileswhenwatchEnabled="true"
277Whenanewwarfileisaddedthewargetsdeployedtothelocalinstance,
278andthendeployedtotheotherinstancesinthecluster.
279WhenawarfileisdeletedfromthewatchDirthewarisundeployedlocally
280andclusterwide
281-->
282
283<!--
284<ClusterclassName="org.apache.catalina.cluster.tcp.SimpleTcpCluster"
285managerClassName="org.apache.catalina.cluster.session.DeltaManager"
286expireSessionsOnShutdown="false"
287useDirtyFlag="true"
288notifyListenersOnReplication="true">
289
290<Membership
291className="org.apache.catalina.cluster.mcast.McastService"
292mcastAddr="228.0.0.4"
293mcastPort="45564"
294mcastFrequency="500"
295mcastDropTime="3000"/>
296
297<Receiver
298className="org.apache.catalina.cluster.tcp.ReplicationListener"
299tcpListenAddress="auto"
300tcpListenPort="4001"
301tcpSelectorTimeout="100"
302tcpThreadCount="6"/>
303
304<Sender
305className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
306replicationMode="pooled"
307ackTimeout="15000"/>
308
309<ValveclassName="org.apache.catalina.cluster.tcp.ReplicationValve"
310filter=".*\.gif;.*\.js;.*\.jpg;.*\.htm;.*\.html;.*\.txt;"/>
311
312<DeployerclassName="org.apache.catalina.cluster.deploy.FarmWarDeployer"
313tempDir="/tmp/war-temp/"
314deployDir="/tmp/war-deploy/"
315watchDir="/tmp/war-listen/"
316watchEnabled="false"/>
317</Cluster>
318-->
319
320
321
322<!--Normally,usersmustauthenticatethemselvestoeachwebapp
323individually.Uncommentthefollowingentryifyouwouldlike
324ausertobeauthenticatedthefirsttimetheyencountera
325resourceprotectedbyasecurityconstraint,andthenhavethat
326useridentitymaintainedacross*all*webapplicationscontained
327inthisvirtualhost.-->
328<!--
329<ValveclassName="org.apache.catalina.authenticator.SingleSignOn"/>
330-->
331
332<!--Accesslogprocessesallrequestsforthisvirtualhost.By
333default,logfilesarecreatedinthe"logs"directoryrelativeto
334$CATALINA_HOME.Ifyouwish,youcanspecifyadifferent
335directorywiththe"directory"attribute.Specifyeitherarelative
336(to$CATALINA_HOME)orabsolutepathtothedesireddirectory.
337-->
338<!--
339<ValveclassName="org.apache.catalina.valves.AccessLogValve"
340directory="logs"prefix="localhost_access_log."suffix=".txt"
341pattern="common"resolveHosts="false"/>
342-->
343
344<!--Accesslogprocessesallrequestsforthisvirtualhost.By
345default,logfilesarecreatedinthe"logs"directoryrelativeto
346$CATALINA_HOME.Ifyouwish,youcanspecifyadifferent
347directorywiththe"directory"attribute.Specifyeitherarelative
348(to$CATALINA_HOME)orabsolutepathtothedesireddirectory.
349Thisaccesslogimplementationisoptimizedformaximumperformance,
350butishardcodedtosupportonlythe"common"and"combined"patterns.
351-->
352<!--
353<ValveclassName="org.apache.catalina.valves.FastCommonAccessLogValve"
354directory="logs"prefix="localhost_access_log."suffix=".txt"
355pattern="common"resolveHosts="false"/>
356-->
357<ContextdocBase="D:\WORKS\EShop\EWebShop"path="/"reloadable="true"
workDir="D:\WORKS\EShop\Tomcat\work\EWebShop">
358</Context>
359</Host>
360<Hostname="yvor.vicp.net"appBase="webapps"unpackWARs="true"autoDeploy="true"xmlValidation="false"
xmlNamespaceAware="false">
361<ContextdocBase="D:\WORKS\YCOE\ycoe"path="/"reloadable="true"workDir="D:\WORKS\YCOE\Tomcat\work\ycoe">
362</Context>
363</Host>
364</Engine>
365</Service>
366</Server>
367
368
可以看到,这里修改了
81行修改了两个参数值:<Connectorport="80"maxHttpHeaderSize="8192"
maxThreads="150"minSpareThreads="25"maxSpareThreads="75"
enableLookups="false"redirectPort="8443"acceptCount="100"
connectionTimeout="20000"disableUploadTimeout="true"URIEncoding="GB2312"/>
修改port是修改Tomcat的服务端口,默认为8080,URIEncoding改为GB2312是为了使用中文路径
但不建议使用.
125行:<Enginename="Catalina"defaultHost="ycoe.vicp.net">
192行:<Hostname="ycoe.vicp.net"appBase="webapps"unpackWARs="true"autoDeploy="true"xmlValidation="false"xmlNamespaceAware="false">
然后再添加360行开始的<Host>元素:<Hostname="yvor.vicp.net"appBase="webapps"unpackWARs="true"autoDeploy="true"
xmlValidation="false"xmlNamespaceAware="false">
<ContextdocBase="D:\WORKS\YCOE\ycoe"path="/"reloadable="true"
workDir="D:\WORKS\YCOE\Tomcat\work\ycoe"></Context>
</Host>
这里是设置我们的第二个虚拟网站的域名.
注:<Context/>里面的内容并不是我们实际应用的,我们可以通过另一种比较方便而且容易修改的方式来设置这些参数.下面我们来做这方面的配置:
1.在%CATALINA_HOME%\conf\Catalina目录下创建ycoe.vicp.net和yvor.vicp.net两个文件夹.
2.在这两个文件夹里面创建ROOT.xml文件(要以ROOT.xml为名称,否则虽然不会出错,但不能用http://ycoe.vicp.net或http://yvor.vicp.net直接访问)
3.ROOT.xml的内容如下:
<?xmlversion='1.0'encoding='utf-8'?>
<ContextdocBase="D:\WORKS\EShop\EWebShop"path="/"reloadable="true"
workDir="D:\WORKS\EShop\Tomcat\work\EWebShop">
</Context>
根据自己的实际情况,设置这里的docBase和workDir的路径.docBase是说明文档的路径,
workDir是网站程序的路径,如果用相对路径,则是在%CATALINA_HOME%\webapp目录下,path是访问的路径
参考官方文档:
AnyXMLfileinthe$CATALINA_HOME/conf/[engine_name]/[host_name]directoryisassumedtocontainaContextelement(anditsassociatedsubelements)
forasinglewebapplication.ThedocBaseattributeofthis<Context>elementwilltypicallybetheabsolute
pathnametoawebapplicationdirectory,ortheabsolutepathnameofawebapplicationarchive(WAR)
file(whichwillnotbeexpanded).
Anywebapplicationarchivefilewithintheapplicationbase(appBase)directorythatdoesnothavea
correspondingdirectoryofthesamename(withoutthe".war"extension)willbeautomaticallyexpanded,
unlesstheunpackWARspropertyissettofalse.IfyouredeployanupdatedWARfile,besuretodeletethe
expandeddirectorywhenrestartingTomcat,sothattheupdatedWARfilewillbere-expanded(notethattheautodeployerwillautomaticallytakecareofthisifitisenabled).
Anysubdirectorywithintheapplicationbasedirectorythatappearstobeanunpackedwebapplication
(thatis,itcontainsa/WEB-INF/web.xmlfile)willreceiveanautomaticallygeneratedContextelement,evenifthisdirectoryisnot
mentionedintheconf/server.xmlfile.ThisgeneratedContextentrywillbeconfiguredaccordingtothe
propertiessetinanyDefaultContextelementnestedinthisHostelement.Thecontextpathforthis
deployedContextwillbeaslashcharacter("/")followedbythedirectoryname,unlessthedirectorynameis
ROOT,inwhichcasethecontextpathwillbeanemptystring("").
你也可以在这两个目录下创建其它xml的文件
但是这时你通过浏览器访问http://ycoe.vicp.net或http://yvor.vicp.net时并不能浏览到你的网页,因为它把这些网址解析到广域网上去了,除非你用域名绑定.
为了让局域本机不把这两个网址解析到广域网上去.我们可以通过以下设置实现(WindowsXP,其它操作系统没有试过):
1.用文本编辑器打开C:\WINDOWS\system32\drivers\etc目录的hosts文件
2.在内容最后另起一行,添加以下内容:
127.0.0.1ycoe.vicp.net
127.0.0.1yvor.vicp.net
可以由上面的注释部分了解它的作用:
#Copyright(c)1993-1999MicrosoftCorp.
#
#ThisisasampleHOSTSfileusedbyMicrosoftTCP/IPforWindows.
#
#ThisfilecontainsthemappingsofIPaddressestohostnames.Each
#entryshouldbekeptonanindividualline.TheIPaddressshould
#beplacedinthefirstcolumnfollowedbythecorrespondinghostname.
#TheIPaddressandthehostnameshouldbeseparatedbyatleastone
#space.
#
#Additionally,comments(suchasthese)maybeinsertedonindividual
#linesorfollowingthemachinenamedenotedbya'#'symbol.
#
#Forexample:
#
#102.54.94.97rhino.acme.com#sourceserver
#38.25.63.10x.acme.com#xclienthost
到这里,全部的配置已经完成了.重启Tomcat,打开http://ycoe.vicp.net或http://yvor.vicp.net就可以看到预期的效果了.呵呵
下载相关文件 http://www.cnblogs.com/Files/ycoe/Catalina.rar