中国最大的web开发资源网站及技术社区,
在网络上找了许久,没有一个真正可以解决tomcat多虚拟站点的配置问题的,经过试验和参考官方网站资料,终于解决了这个问题.
参考资料:apache tomcat文档http://tomcat.apache.org/tomcat-5.0-doc/config/host.html
在文中有这么一段话:
one or more host elements are nested inside an engine element. inside the host element, you can nest context elements for the web applications associated with this virtual host. exactly one of the hosts associated with each engine must have a name matching the defaulthost attribute of that engine.
译文:engine元素中需要一个或多个host元素,在host元素里面,你必需有context元素让网站应用程序与虚拟主机连接上,严密地说,每一个主机所关联的引擎必须有一个名字跟那个引擎默认的主机属性匹配 .
可知,在engine元素里面可以有多个host,那么说,可以有在一个engine里面设置多个服务器了,这正是我们需要的.每个host元素里面要有一个context元素.
根据conf/server.xml里面的说明和范例,我样可以编写出下面一个配置文件:
1<!-- example server configuration file -->
2<!-- note that component elements are nested corresponding to their
3 parent-child relationships with each other -->
4
5<!-- a "server" is a singleton element that represents the entire jvm,
6 which may contain one or more "service" instances. the server
7 listens for a shutdown command on the indicated port.
8
9 note: a "server" is not itself a "container", so you may not
10 define subcomponents such as "valves" or "loggers" at this level.
11 -->
12
13<server port="8005" shutdown="shutdown">
14
15 <!-- comment these entries out to disable jmx mbeans support used for the
16 administration web application -->
17 <listener classname="org.apache.catalina.core.aprlifecyclelistener" />
18 <listener classname="org.apache.catalina.mbeans.serverlifecyclelistener" />
19 <listener classname="org.apache.catalina.mbeans.globalresourceslifecyclelistener" />
20 <listener classname="org.apache.catalina.storeconfig.storeconfiglifecyclelistener"/>
21
22 <!-- global jndi resources -->
23 <globalnamingresources>
24
25 <!-- test entry for demonstration purposes -->
26 <environment name="simplevalue" type="java.lang.integer" value="30"/>
27
28 <!-- editable user database that can also be used by
29 userdatabaserealm to authenticate users -->
30 <resource name="userdatabase" auth="container"
31 type="org.apache.catalina.userdatabase"
32 description="user database that can be updated and saved"
33 factory="org.apache.catalina.users.memoryuserdatabasefactory"
34 pathname="conf/tomcat-users.xml" />
35
36 </globalnamingresources>
37
38 <!-- a "service" is a collection of one or more "connectors" that share
39 a single "container" (and therefore the web applications visible
40 within that container). normally, that container is an "engine",
41 but this is not required.
42
43 note: a "service" is not itself a "container", so you may not
44 define subcomponents such as "valves" or "loggers" at this level.
45 -->
46
47 <!-- define the tomcat stand-alone service -->
48 <service name="catalina">
49
50 <!-- a "connector" represents an endpoint by which requests are received
51 and responses are returned. each connector passes requests on to the
52 associated "container" (normally an engine) for processing.
53
54 by default, a non-ssl http/1.1 connector is established on port 8080.
55 you can also enable an ssl http/1.1 connector on port 8443 by
56 following the instructions below and uncommenting the second connector
57 entry. ssl support requires the following steps (see the ssl config
58 howto in the tomcat 5 documentation bundle for more detailed
59 instructions):
60 * if your jdk version 1.3 or prior, download and install jsse 1.0.2 or
61 later, and put the jar files into "$java_home/jre/lib/ext".
62 * execute:
63 %java_home%/bin/keytool -genkey -alias tomcat -keyalg rsa (windows)
64 $java_home/bin/keytool -genkey -alias tomcat -keyalg rsa (unix)
65 with a password value of "changeit" for both the certificate and
66 the keystore itself.
67
68 by default, dns lookups are enabled when a web application calls
69 request.getremotehost(). this can have an adverse impact on
70 performance, so you can disable it by setting the
71 "enablelookups" attribute to "false". when dns lookups are disabled,
72 request.getremotehost() will return the string version of the
73 ip address of the remote client.
74 -->
75
76 <!-- define a non-ssl http/1.1 connector on port 8080 -->
77 <connector
78port="80" maxhttpheadersize="8192"
79 maxthreads="150" minsparethreads="25" maxsparethreads="75"
80 enablelookups="false" redirectport="8443" acceptcount="100"
81 connectiontimeout="20000" disableuploadtimeout="true" uriencoding="gb2312"/>
82 <!-- note : to disable connection timeouts, set connectiontimeout value
83 to 0 -->
84
85 <!-- note : to use gzip compression you could set the following properties :
86
87 compression="on"
88 compressionminsize="2048"
89 nocompressionuseragents="gozilla, traviata"
90 compressablemimetype="text/html,text/xml"
91 -->
92
93 <!-- define a ssl http/1.1 connector on port 8443 -->
94 <!--
95 <connector port="8443" maxhttpheadersize="8192"
96 maxthreads="150" minsparethreads="25" maxsparethreads="75"
97 enablelookups="false" disableuploadtimeout="true"
98 acceptcount="100" scheme="https" secure="true"
99 clientauth="false" sslprotocol="tls" />
100 -->
101
102 <!-- define an ajp 1.3 connector on port 8009 -->
103 <connector port="8009"
104 enablelookups="false" redirectport="8443" protocol="ajp/1.3" />
105
106 <!-- define a proxied http/1.1 connector on port 8082 -->
107 <!-- see proxy documentation for more information about using this. -->
108 <!--
109 <connector port="8082"
110 maxthreads="150" minsparethreads="25" maxsparethreads="75"
111 enablelookups="false" acceptcount="100" connectiontimeout="20000"
112 proxyport="80" disableuploadtimeout="true" />
113 -->
114
115 <!-- an engine represents the entry point (within catalina) that processes
116 every request. the engine implementation for tomcat stand alone
117 analyzes the http headers included with the request, and passes them
118 on to the appropriate host (virtual host). -->
119
120 <!-- you should set jvmroute to support load-balancing via ajp ie :
121 <engine name="standalone" defaulthost="localhost" jvmroute="jvm1">
122 -->
123
124 <!-- define the top level container in our container hierarchy -->
125 <engine name="catalina" defaulthost="ycoe.vicp.net">
126
127 <!-- the request dumper valve dumps useful debugging information about
128 the request headers and cookies that were received, and the response
129 headers and cookies that were sent, for all requests received by
130 this instance of tomcat. if you care only about requests to a
131 particular virtual host, or a particular application, nest this
132 element inside the corresponding <host> or <context> entry instead.
133
134 for a similar mechanism that is portable to all servlet 2.4
135 containers, check out the "requestdumperfilter" filter in the
136 example application (the source for this filter may be found in
137 "$catalina_home/webapps/examples/web-inf/classes/filters").
138
139 request dumping is disabled by default. uncomment the following
140 element to enable it. -->
141 <!--
142 <valve classname="org.apache.catalina.valves.requestdumpervalve"/>
143 -->
144
145 <!-- because this realm is here, an instance will be shared globally -->
146
147 <!-- this realm uses the userdatabase configured in the global jndi
148 resources under the key "userdatabase". any edits
149 that are performed against this userdatabase are immediately
150 available for use by the realm. -->
151 <realm classname="org.apache.catalina.realm.userdatabaserealm"
152 resourcename="userdatabase"/>
153
154 <!-- comment out the old realm but leave here for now in case we
155 need to go back quickly -->
156 <!--
157 <realm classname="org.apache.catalina.realm.memoryrealm" />
158 -->
159
160 <!-- replace the above realm with one of the following to get a realm
161 stored in a database and accessed via jdbc -->
162
163 <!--
164 <realm classname="org.apache.catalina.realm.jdbcrealm"
165 drivername="org.gjt.mm.mysql.driver"
166 connectionurl="jdbc:mysql://localhost/authority"
167 connectionname="test" connectionpassword="test"
168 usertable="users" usernamecol="user_name" usercredcol="user_pass"
169 userroletable="user_roles" rolenamecol="role_name" />
170 -->
171
172 <!--
173 <realm classname="org.apache.catalina.realm.jdbcrealm"
174 drivername="oracle.jdbc.driver.oracledriver"
175 connectionurl="jdbc:oracle:thin:@ntserver:1521:orcl"
176 connectionname="scott" connectionpassword="tiger"
177 usertable="users" usernamecol="user_name" usercredcol="user_pass"
178 userroletable="user_roles" rolenamecol="role_name" />
179 -->
180
181 <!--
182 <realm classname="org.apache.catalina.realm.jdbcrealm"
183 drivername="sun.jdbc.odbc.jdbcodbcdriver"
184 connectionurl="jdbc:odbc:catalina"
185 usertable="users" usernamecol="user_name" usercredcol="user_pass"
186 userroletable="user_roles" rolenamecol="role_name" />
187 -->
188
189 <!-- define the default virtual host
190 note: xml schema validation will not work with xerces 2.2.
191 -->
192 <host name="ycoe.vicp.net" appbase="webapps"
193 unpackwars="true" autodeploy="true"
194 xmlvalidation="false" xmlnamespaceaware="false">
195
196 <!-- defines a cluster for this node,
197 by defining this element, means that every manager will be changed.
198 so when running a cluster, only make sure that you have webapps in there
199 that need to be clustered and remove the other ones.
200 a cluster has the following parameters:
201
202 classname = the fully qualified name of the cluster class
203
204 name = a descriptive name for your cluster, can be anything
205
206 mcastaddr = the multicast address, has to be the same for all the nodes
207
208 mcastport = the multicast port, has to be the same for all the nodes
209
210 mcastbindaddr = bind the multicast socket to a specific address
211
212 mcastttl = the multicast ttl if you want to limit your broadcast
213
214 mcastsotimeout = the multicast readtimeout
215
216 mcastfrequency = the number of milliseconds in between sending a "i'm alive" heartbeat
217
218 mcastdroptime = the number a milliseconds before a node is considered "dead" if no heartbeat is received
219
220 tcpthreadcount = the number of threads to handle incoming replication requests, optimal would be the same
amount of threads as nodes
221
222 tcplistenaddress = the listen address (bind address) for tcp cluster request on this host,
223 in case of multiple ethernet cards.
224 auto means that address becomes
225 inetaddress.getlocalhost().gethostaddress()
226
227 tcplistenport = the tcp listen port
228
229 tcpselectortimeout = the timeout (ms) for the selector.select() method in case the os
230 has a wakup bug in java.nio. set to 0 for no timeout
231
232 printtoscreen = true means that managers will also print to std.out
233
234 expiresessionsonshutdown = true means that
235
236 usedirtyflag = true means that we only replicate a session after setattribute,removeattribute has been called.
237 false means to replicate the session after each request.
238 false means that replication would work for the following piece of code: (only for simpletcpreplicationmanager)
239 <%
240 hashmap map = (hashmap)session.getattribute("map");
241 map.put("key","value");
242 %>
243 replicationmode = can be either 'pooled', 'synchronous' or 'asynchronous'.
244 * pooled means that the replication happens using several sockets in a synchronous way. ie,
the data gets replicated, then the request return. this is the same as the 'synchronous' setting except it uses a pool of sockets,
hence it is multithreaded. this is the fastest and safest configuration. to use this, also increase the nr of tcp threads
that you have dealing with replication.
245 * synchronous means that the thread that executes the request, is also the
246 thread the replicates the data to the other nodes, and will not return until all
247 nodes have received the information.
248 * asynchronous means that there is a specific 'sender' thread for each cluster node,
249 so the request thread will queue the replication request into a "smart" queue,
250 and then return to the client.
251 the "smart" queue is a queue where when a session is added to the queue, and the same session
252 already exists in the queue from a previous request, that session will be replaced
253 in the queue instead of replicating two requests. this almost never happens, unless there is a
254 large network delay.
255 -->
256 <!--
257 when configuring for clustering, you also add in a valve to catch all the requests
258 coming in, at the end of the request, the session may or may not be replicated.
259 a session is replicated if and only if all the conditions are met:
260 1. usedirtyflag is true or setattribute or removeattribute has been called and
261 2. a session exists (has been created)
262 3. the request is not trapped by the "filter" attribute
263
264 the filter attribute is to filter out requests that could not modify the session,
265 hence we don't replicate the session after the end of this request.
266 the filter is negative, ie, anything you put in the filter, you mean to filter out,
267 ie, no replication will be done on requests that match one of the filters.
268 the filter attribute is delimited by ;, so you can't escape out ; even if you wanted to.
269
270 filter=".*/.gif;.*/.js;" means that we will not replicate the session after requests with the uri
271 ending with .gif and .js are intercepted.
272
273 the deployer element can be used to deploy apps cluster wide.
274 currently the deployment only deploys/undeploys to working members in the cluster
275 so no wars are copied upons startup of a broken node.
276 the deployer watches a directory (watchdir) for war files when watchenabled="true"
277 when a new war file is added the war gets deployed to the local instance,
278 and then deployed to the other instances in the cluster.
279 when a war file is deleted from the watchdir the war is undeployed locally
280 and cluster wide
281 -->
282
283 <!--
284 <cluster classname="org.apache.catalina.cluster.tcp.simpletcpcluster"
285 managerclassname="org.apache.catalina.cluster.session.deltamanager"
286 expiresessionsonshutdown="false"
287 usedirtyflag="true"
288 notifylistenersonreplication="true">
289
290 <membership
291 classname="org.apache.catalina.cluster.mcast.mcastservice"
292 mcastaddr="228.0.0.4"
293 mcastport="45564"
294 mcastfrequency="500"
295 mcastdroptime="3000"/>
296
297 <receiver
298 classname="org.apache.catalina.cluster.tcp.replicationlistener"
299 tcplistenaddress="auto"
300 tcplistenport="4001"
301 tcpselectortimeout="100"
302 tcpthreadcount="6"/>
303
304 <sender
305 classname="org.apache.catalina.cluster.tcp.replicationtransmitter"
306 replicationmode="pooled"
307 acktimeout="15000"/>
308
309 <valve classname="org.apache.catalina.cluster.tcp.replicationvalve"
310 filter=".*/.gif;.*/.js;.*/.jpg;.*/.htm;.*/.html;.*/.txt;"/>
311
312 <deployer classname="org.apache.catalina.cluster.deploy.farmwardeployer"
313 tempdir="/tmp/war-temp/"
314 deploydir="/tmp/war-deploy/"
315 watchdir="/tmp/war-listen/"
316 watchenabled="false"/>
317 </cluster>
318 -->
319
320
321
322 <!-- normally, users must authenticate themselves to each web app
323 individually. uncomment the following entry if you would like
324 a user to be authenticated the first time they encounter a
325 resource protected by a security constraint, and then have that
326 user identity maintained across *all* web applications contained
327 in this virtual host. -->
328 <!--
329 <valve classname="org.apache.catalina.authenticator.singlesignon" />
330 -->
331
332 <!-- access log processes all requests for this virtual host. by
333 default, log files are created in the "logs" directory relative to
334 $catalina_home. if you wish, you can specify a different
335 directory with the "directory" attribute. specify either a relative
336 (to $catalina_home) or absolute path to the desired directory.
337 -->
338 <!--
339 <valve classname="org.apache.catalina.valves.accesslogvalve"
340 directory="logs" prefix="localhost_access_log." suffix=".txt"
341 pattern="common" resolvehosts="false"/>
342 -->
343
344 <!-- access log processes all requests for this virtual host. by
345 default, log files are created in the "logs" directory relative to
346 $catalina_home. if you wish, you can specify a different
347 directory with the "directory" attribute. specify either a relative
348 (to $catalina_home) or absolute path to the desired directory.
349 this access log implementation is optimized for maximum performance,
350 but is hardcoded to support only the "common" and "combined" patterns.
351 -->
352 <!--
353 <valve classname="org.apache.catalina.valves.fastcommonaccesslogvalve"
354 directory="logs" prefix="localhost_access_log." suffix=".txt"
355 pattern="common" resolvehosts="false"/>
356 -->
357 <context docbase="d:/works/eshop/ewebshop" path="/" reloadable="true"
workdir="d:/works/eshop/tomcat/work/ewebshop">
358 </context>
359 </host>
360<host name="yvor.vicp.net" appbase="webapps"unpackwars="true" autodeploy="true"xmlvalidation="false"
xmlnamespaceaware="false">
361 <context docbase="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行修改了两个参数值:<connector port="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行:<engine name="catalina" defaulthost="ycoe.vicp.net">
192行:<host name="ycoe.vicp.net" appbase="webapps" unpackwars="true" autodeploy="true" xmlvalidation="false" xmlnamespaceaware="false">
然后再添加360行开始的<host>元素:<host name="yvor.vicp.net" appbase="webapps"unpackwars="true" autodeploy="true"
xmlvalidation="false" xmlnamespaceaware="false">
<context docbase="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的内容如下:
<?xml version='1.0' encoding='utf-8'?>
<context docbase="d:/works/eshop/ewebshop" path="/" reloadable="true"
workdir="d:/works/eshop/tomcat/work/ewebshop">
</context>
根据自己的实际情况,设置这里的docbase 和workdir的路径.docbase是说明文档的路径,workdir是网站程序的路径,如果用相对路径,则是在%catalina_home %/webapp目录下,path是访问的路径
参考官方文档:
any xml file in the $catalina_home/conf/[engine_name]/[host_name] directory is assumed to contain a context element (and its associated subelements) for a single web application. the docbase attribute of this <context> element will typically be the absolute pathname to a web application directory, or the absolute pathname of a web application archive (war) file (which will not be expanded).
any web application archive file within the application base (appbase) directory that does not have a corresponding directory of the same name (without the ".war" extension) will be automatically expanded, unless the unpackwars property is set to false. if you redeploy an updated war file, be sure to delete the expanded directory when restarting tomcat, so that the updated war file will be re-expanded (note that the auto deployer will automatically take care of this if it is enabled).
any subdirectory within the application base directory that appears to be an unpacked web application (that is, it contains a /web-inf/web.xml file) will receive an automatically generated context element, even if this directory is not mentioned in the conf/server.xml file. this generated context entry will be configured according to the properties set in any defaultcontext element nested in this host element. the context path for this deployed context will be a slash character ("/") followed by the directory name, unless the directory name is root, in which case the context path will be an empty string ("").
你也可以在这两个目录下创建其它xml的文件
但是这时你通过浏览器访问http://ycoe.vicp.net或http://yvor.vicp.net时并不能浏览到你的网页,因为它把这些网址解析到广域网上去了,除非你用域名绑定.
为了让局域本机不把这两个网址解析到广域网上去.我们可以通过以下设置实现(windows xp,其它操作系统没有试过):
1.用文本编辑器打开c:/windows/system32/drivers/etc目录的hosts文件
2.在内容最后另起一行,添加以下内容:
127.0.0.1 ycoe.vicp.net
127.0.0.1 yvor.vicp.net
可以由上面的注释部分了解它的作用:
# copyright (c) 1993-1999 microsoft corp.
#
# this is a sample hosts file used by microsoft tcp/ip for windows.
#
# this file contains the mappings of ip addresses to host names. each
# entry should be kept on an individual line. the ip address should
# be placed in the first column followed by the corresponding host name.
# the ip address and the host name should be separated by at least one
# space.
#
# additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# for example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host
到这里,全部的配置已经完成了.重启tomcat,打开http://ycoe.vicp.net或http://yvor.vicp.net就可以看到预期的效果了.呵呵
下载相关文件http://www.cnblogs.com/files/ycoe/catalina.rar