Implementing Virtual Hosting with Tomcat

Tomcat can work either in stand-alone mode, in which it serves static pages along with JSP pages/servlets, or in conjunction with a Web server such as Apache. Chapter 12 have more details on this.

If Tomcat is to provide virtual hosting support, then when a request comes for a particular resource on one of Tomcat’s virtual hosts, Tomcat should be able to successfully obtain the host that the request was for and fetch the required resource from the host’s document base.

When working in conjunction with another Web server like Apache, the Web server handles the virtual hosts and processing of subsequent static pages, as you saw in Chapter 12. Tomcat then handles the servlets and JSP pages while distinguishing the various hosts involved.

Creating an Example Configuration

You’ll configure Tomcat to serve three hosts: www.tomcatbook.com, www.catalinabook.com, and www.jasperbook.com, each running on the same machine with a common IP address. This machine may be part of your network, or it may be the local machine with the 127.0.0.1 local loopback address. If it’s part of your network, you should ensure you have set up a DNS entry for each host. (Listing 13-8 later in the chapter shows an example of this.)

These domains will be hosted in a directory outside the Tomcat base directory. Each of the domains has its own document area in /home/sites/<domain-name>. Web applications are deployed in the webapps folder under this hierarchy. If you were planning on using Apache with this setup, you could also consider a /home/sites/<domain-name>/web directory as Apache’s document root. I’ll get to this in the “Implementing Virtual Hosting with Apache and Tomcat” section.

You may even want to place the static pages into a separate directory anyway (say the ROOT Web application), because in many shared hosting scenarios the hosting requirement of the clients includes Tomcat support, as an additional feature to their regular Web needs. Clients who want to add Web applications can drop their WAR files in the webapps directory without mixing them up with the static content. Figure 13-5 shows the general layout of the sample shared hosts on the Tomcat server.

image from book
Figure 13-5: The general layout of the example shared hosts

You’ll need a way to identify which host you have accessed to determine if your configuration is correct. Therefore, each host should have a ROOT Web application with an index.html file that points to a JSP page in the dynamic section, as shown in Listing 13-1.

Listing 13-1: The index.hml Page for Shared Hosting

image from book
 <html>    <head><title>Welcome to catalinabook.com</title>    <body>      <h1>Welcome to catalinabook.com</h1>      <hr/>      <p>        Click <a href="jsp/index.jsp">here</a>        to access the dynamic section of the site.      </p>    </body>  </html> 
image from book

Remember to change the name of the host. Feel free to change these setup details to suit your own server hosting policy. Just remember to change the settings as given in Listing 13-5 accordingly.

The JSP page is common to all the hosts and should be placed in the jsp Web application. Listing 13-2 shows this page.

Listing 13-2: The index.jsp Page That’s Common to All the Hosts

image from book
 <html>    <head>      <title>        Welcome to ${pageContext.servletContext.servletContextName}      </title>    <body>      <h1>Welcome to ${pageContext.servletContext.servletContextName}</h1>      <hr/>    </body>  </html> 
image from book

The EL segments obtain the name of the host so that you can see that the virtual hosting is working and that JSP pages are producing dynamic content. The servletContextName property is set in each Web application’s web.xml file.

Finally, you don’t necessarily need a web.xml file for each of these simple Web applications, though to follow good practice you should add one such as is shown in Listing 13-3 and Listing 13-4.

Listing 13-3: A web.xml for the ROOT Web Application

image from book
 <?xml version="1.0" encoding="ISO-8859-1"?>  <web-app xmlns="http://java.sun.com/xml/ns/j2ee"           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"           xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee           http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">    <display-name>ROOT web application</display-name>    <description>      Users should place their static HTML files here.    </description>  </web-app> 
image from book

Listing 13-4: A web.xml for the jsp Web Application

image from book
 <?xml version="1.0" encoding="ISO-8859-1"?>  <web-app xmlns="http://java.sun.com/xml/ns/j2ee"           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"           xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee           http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">    <display-name>the jsp web application on catalinabook.com</display-name>    <description>      A dynamic web application.    </description>  </web-app> 
image from book

You should change the <display-name> setting for each host as follows. This will be displayed to show that each host is serving a different dynamic page.

You now have all you need to implement virtual hosting. Figure 13-6 shows you how your final configuration should look for each host.

image from book
Figure 13-6: The final Web application configuration

Here you can see that the static HTML files are separated from any dynamic content. You can then host static Web sites alongside dynamic Web sites by placing subdirectories in the ROOT Web application should you choose to do so.

Setting Up the Virtual Hosting

You define virtual hosts in server.xml. For this example you’ll see a complete server.xml file written from scratch. Feel free to add the settings to your existing server.xml.

Listing 13-5 shows the setup for the first virtual host. To add the other two, simply duplicate the settings appropriately.

Listing 13-5: Creating a Virtual Host in server.xml

image from book
 <Server port="8005" shutdown="SHUTDOWN">    <Service name="Virtual Hosting Tomcat">      <Connector port="8080"                 maxThreads="150" minSpareThreads="25" maxSpareThreads="75"                 enableLookups="false" redirectPort="8443" acceptCount="100"                 debug="0" connectionTimeout="20000"                 disableUploadTimeout="true" />      <Engine name="Catalina" defaultHost="www.catalinabook.com">        <!-- Global logger unless overridden at lower levels -->        <!-- Tomcat 5.0.x only -->        <Logger className="org.apache.catalina.logger.FileLogger"                prefix="catalina_log." suffix=".txt"                timestamp="true"/>        <Host name="www.catalinabook.com" debug="0"              appBase="C:/home/sites/catalinabook.com/webapps"              unpackWARs="true">          <Valve className="org.apache.catalina.valves.AccessLogValve"                 directory="C:/home/sites/catalinabook.com/logs"                 prefix="catalinabook.com.access."                 suffix=".log"                 pattern="common"/>           <!-- Tomcat 5.0.x only -->           <Logger className="org.apache.catalina.logger.FileLogger"                   directory="C:/home/sites/catalinabook.com/logs"                   prefix="catalinabook.com."                   suffix=".log"                   timestamp="true"/>        </Host>        <!-- The other two virtual hosts go here -->      </Engine>    </Service>  </Server> 
image from book

The connector is copied from the default server.xml file and listens for HTTP requests on port 8080 as usual. The engine setting configures www.catalinabook.com as the default host. The engine examines the HTTP headers, especially the Host: header, and determines which of the virtual host definitions should receive the request. If none of the virtual host seems to match the request headers, the engine passes on the request to the default host. The value of this attribute must match a <Host> definition in the engine. Then the host setting assigns a home directory for webapps and sets an access log and a general log.

For Tomcat 5.5 logging, follow the instructions in Listing 13-6 in CATALINA_HOME/common/classes.

Listing 13-6: log4j.properties Logging File for Virtual Hosting

image from book
 #--------------------------------#  # Set the root logger for Tomcat #  #--------------------------------#  log4j.rootLogger=INFO, TomcatINFO, TomcatERROR  #---------------------------------------------#  # Send all INFO messages and above to a file  #  #---------------------------------------------#  log4j.appender.TomcatINFO=org.apache.log4j.FileAppender  log4j.appender.TomcatINFO.File=C:/jakarta-tomcat-5.5.3/logs/catalina_log.txt  # Use the simple layout  log4j.appender.TomcatINFO.layout=org.apache.log4j.SimpleLayout  #--------------------------------------------------#  # Send all ERROR messages and above to the console #  #--------------------------------------------------#  log4j.appender.TomcatERROR=org.apache.log4j.ConsoleAppender  log4j.appender.TomcatERROR.Target=System.out  log4j.appender.TomcatERROR.layout=org.apache.log4j.PatternLayout  log4j.appender.TomcatERROR.layout.ConversionPattern=%p: %m: %d{ABSOLUTE} %n  log4j.appender.TomcatERROR.Threshold=ERROR  #--------------------------------------------#  # Define a log for the catalinabook.com host #  #--------------------------------------------#  log4j.logger.org.apache.catalina.core.ContainerBase.  [Catalina].[www.catalinabook.com]=INFO,catalinabook  # Log to a file  log4j.appender.catalinabook=org.apache.log4j.FileAppender  log4j.appender.catalinabook.  File=C:/home/sites/catalinabook.com/logs/catalinabook.com.log  # Use the simple layout  log4j.appender.catalinabook.layout=org.apache.log4j.SimpleLayout  #------------------------------------------#  # Define a log for the jasperbook.com host #  #------------------------------------------#  log4j.logger.org.apache.catalina.core.ContainerBase.  [Catalina].[www.jasperbook.com]=INFO,jasperbook  # Log to a file  log4j.appender.jasperbook=org.apache.log4j.FileAppender  log4j.appender.jasperbook.File=C:/home/sites/jasperbook.com/logs/jasperbook.com.log  # Use the simple layout  log4j.appender.jasperbook.layout=org.apache.log4j.SimpleLayout  #------------------------------------------#  # Define a log for the tomcatbook.com host #  #------------------------------------------#  log4j.logger.org.apache.catalina.core.ContainerBase.  [Catalina].[www.tomcatbook.com]=INFO,tomcatbook  # Log to a file  log4j.appender.tomcatbook=org.apache.log4j.FileAppender  log4j.appender.tomcatbook.File=C:/home/sites/tomcatbook.com/logs/tomcatbook.com.log  # Use the simple layout  log4j.appender.tomcatbook.layout=org.apache.log4j.SimpleLayout 
image from book

This file sets the same loggers as the <Logger> components in Listing 13-5.

To configure contexts for catalinabook.com, place a context XML file in CATALINA_HOME/conf/Catalina/www.catalinabook.com. Note the name of the host is the name of the last directory. Listing 13-7 shows the jsp.xml configuration file, and Listing 13-8 shows the ROOT.xml configuration file.

Listing 13-7: The jsp.xml Configuration File

image from book
 <Context path="/jsp" docBase="jsp" debug="0" /> 
image from book

Listing 13-8: The ROOT.xml Configuration File

image from book
 <Context displayName="Welcome to Tomcat" docBase="ROOT" path="" /> 
image from book

These files are common to all the Web applications, so place them in CATALINA_HOME/conf/Catalina/www.jasperbook.com and CATALINA_HOME/conf/Catalina/www.tomcatbook.com as well.

Testing the Virtual Hosting

If you don’t have your DNS server set up to point to your machine, you can alter your local hosts file to simulate a DNS server. On Unix systems this is the /etc/hosts file, and on Windows it’s WinNT/system32/drivers/etc/hosts (or equivalent on older systems). Listing 13-9 shows the entries in the hosts file that map the three hosts to your local machine’s IP address.

Listing 13-9: An Example Hosts File

image from book
 127.0.0.1       localhost  127.0.0.1       www.catalinabook.com  127.0.0.1       www.jasperbook.com  127.0.0.1       www.tomcatbook.com 
image from book

Start Tomcat, and browse to one of the virtual hosts as shown in Figure 13-7. Remember that Tomcat is still listening on port 8080.

image from book
Figure 13-7: The index page of www.jasperbook.com

Here you can see that the correct index page is shown for www.jasperbook.com. Click the link to try the JSP page, as shown in Figure 13-8.

image from book
Figure 13-8: The dynamic JSP page of www.jasperbook.com

Again, this is the expected behavior, so the dynamic part of the virtual host is working. Try the other hosts to confirm that they’re also working and examine their access logs.

You should then check that the defaultHost setting of the <Engine> element is working properly. Try to access the dynamic section on IP address 127.0.0.1 (or whatever you’ve set your machine’s IP address to be). You should see the www.catalinabook.com page, as shown in Figure 13-9.

image from book
Figure 13-9: Accessing the default host using an IP address



Pro Jakarta Tomcat 5
Pro Apache Tomcat 5/5.5 (Experts Voice in Java)
ISBN: 1590593316
EAN: 2147483647
Year: 2004
Pages: 94

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net