Tomcat’s component-based architecture considerably simplifies configuration. Any properties that are set on the outer components are inherited by the inner components. For example, a listener that’s configured in an engine will be used by a nested host component.
However, if you need a lower-level component to have its own setup, you can override the outer configuration by adding components to the inner component. For example, you could set a realm on a context component to override the realm configured at the engine level. This means that the Web applications running within this context will use the newly defined realm instead of the outer one.
This component-based model lends itself to XML configuration because of XML’s hierarchical nature. Each component is represented by an element in an XML file, which makes it easy to insert and remove components from a server as appropriate. The name of the file that does this job in Tomcat is server.xml, which Tomcat reads at startup.
Note | DTD or schema exists for server.xml because the attributes of certain elements depend on the class implementing the component that the element represents. |
Tomcat comes bundled with a default server.xml file ready to run on your machine. It defines a “Catalina” service, a “Catalina” engine, and a “localhost” host. It also contains two loggers (Tomcat 5.0.x only), one for the engine and one at the host level, which overrides the engine’s logger, and a memory realm for user authentication. A number of other options have been commented out by default but are well commented.
Tomcat also comes with a file called server-minimal.xml, which is a stripped-down version of the configuration file on which you can base your own settings.
Let’s take a closer look at how to configure a server by going through the server.xml file that comes with Tomcat. As you’ll recall from Chapter 1, a server component is a top-level component, and any Tomcat instances can have only one server component. This means that the <Server> element in server.xml is the root element.
<Server port="8005" shutdown="SHUTDOWN" debug="0">
The <Server> element represents the JVM and listens to port 8005 for a shutdown command, which will contain the text SHUTDOWN. This provides a graceful way for an administrator (or management console software) to shut down this Tomcat server instance. The server instance won’t print debugging messages to the log because debug is set to 0. Note that at the time of writing Tomcat 5.5 still has the debug attribute set, even though it does nothing. (This caveat applies to all the components in Table 4-1.)
Attribute | Description | Required? |
---|---|---|
className | The Java class for the server to use. This class must implement the org.apache.catalina.Server interface. The standard implementation is used by default. | No |
debug | Tomcat 5.0.x only. The level of debug information logged by the server. The levels are 1 (errors), 2 (warnings), 3 (information), and 4 (debug). These correspond to the levels of debugging in the logger component. The default is zero, meaning no debugging (though the associated logger will still log fatal messages). | No |
port | The TCP/IP port to listen to for the command specified by the shutdown attribute before shutting down gracefully. This command must come from the same physical server machine on which Tomcat is running. This provides a certain level of security when used in combination with the shutdown attribute. | Yes |
shutdown | The command string that must be sent to the port number specified by the port attribute. | Yes |
Table 4-1 lists the possible attributes of the <Server> element.
Table 4-2 lists the subelements of the <Server> element.
Subelement | Description | Number |
---|---|---|
<GlobalNamingResources> | The global JNDI resources for this server | 1 |
<Service> | A grouping of connectors associated with an engine | 1 or more |
JNDI is an API used for looking up information via a naming and directory service. It’s a platform-independent API, much like JDBC, and it’s designed to work with any compatible naming and directory service—regardless of its native interface API. Some common information you can store and retrieve through JNDI includes the following:
Usernames and passwords
An access control policy, such as the Tomcat user and role mechanism
Organizational directories
Servers (databases, and so on)
Printers
Java objects, such as EJBs
JNDI allows you to avoid the problem of programming for the native interfaces of specific platforms and as such simplifies the process immeasurably. JNDI acts as a layer on top of the native interfaces and translates between the Java classes and the naming servers on the server platform, thus presenting Tomcat with a uniform view of the naming and directory service no matter what the underlying system is.
Additionally, many Java applications use JNDI to locate resources without the need for an underlying naming service. This means a Java application can access resources without knowing their underlying setup or location. For example, a database reference is looked up using its JNDI name only, so it doesn’t matter what the underlying database is or what the driver is. This allows programmers to decouple their applications from hard-coded system resources. Figure 4-1 shows JNDI as a directory service and as a Java lookup mechanism.
Figure 4-1: JNDI
Once the application has the database reference, it can connect to the database directly using JDBC. A constant stored as a JNDI resource can be used across all the Web applications running on a server, as well as by any other Java applications that require it.
Tomcat, and the Web applications that run on it, uses the JNDI resource lookup mechanism extensively.
You configure the server’s global JNDI resources with the <GlobalNamingResources> element.
<GlobalNamingResources>
Table 4-3 shows the subelements of <GlobalNamingResources>.
Subelement | Description | Number |
---|---|---|
<Environment> | A global variable | 0 or more |
<Resource> | A global JNDI resource | 0 or more |
The first type of resource is a serverwide variable. This variable must be of one of the primitive wrapper types that are specified for environment entries in the Servlet specification. You use an <Environment> entry to specify this kind of resource.
<Environment name="simpleValue" type="java.lang.Integer" value="30"/>
This environment entry is called simpleValue, is of type java.lang.Integer, and has the value 30. It’s looked up using the java:comp/env/simpleValue string.
Table 4-4 specifies the attributes that <Environment> can take.
Attribute | Description | Required? |
---|---|---|
description | A description of this environment entry. | No |
name | The name of the environment entry, relative to the java:comp/env context. | Yes |
override | Set this to false if you don’t want a Web application deployment descriptor to override this value. The default is true. | No |
type | The fully qualified Java class type of this entry. Must be one of the legal values specified in the Servlet specification for Web application deployment descriptor environment entries: java.lang.Boolean, java.lang.Byte, java.lang.Character, java.lang.Double, java.lang.Float, java.lang.Integer, java.lang.Long, java.lang.Short, and java.lang.String. | Yes |
value | The value of this entry. | Yes |
Global resources can include JDBC data sources, Enterprise JavaBean (EJB) references, and user authentication databases. You define them with a <Resource> element, and you must also define a set of resource parameters to configure the object factory for this resource type. You’ll see how this is done next.
<Resource name="UserDatabase" auth="Container" type="org.apache.catalina.UserDatabase" description="User database that can be updated and saved"> </Resource>
This is a user database for authenticating users against and is set as the default for the Catalina engine further down in server.xml.
Table 4-5 describes the attributes that a <Resource> element can take.
Attribute | Description | Required? |
---|---|---|
auth | Specifies whether the Web application signs onto the corresponding resource manager programmatically or whether the container will sign onto the resource manager on behalf of the application. The value of this attribute must be Application or Container. This attribute is required if the Web application uses a <resource-ref> element in the Web application deployment descriptor but is optional if the application uses a <resource-env-ref> instead. | No |
description | A description of this resource. | No |
name | The name of the resource to be created. | Yes |
scope | Specifies whether connections obtained through this resource manager can be shared. The value of this attribute must be Shareable or Unshareable. The default is Shareable. | No |
type | The fully qualified Java class name of this resource. | Yes |
To configure the parameters that go along with a global JNDI resource, you use the <ResourceParams> element.
<ResourceParams name="UserDatabase"> <parameter> <name>factory</name> <value>org.apache.catalina.users.MemoryUserDatabaseFactory</value> </parameter> <parameter> <name>pathname</name> <value>conf/tomcat-users.xml</value> </parameter> </ResourceParams> </GlobalNamingResources>
These resource parameters are associated with the UserDatabase resource. They specify the factory class for providing instances of the resource class and specify where the user authentication file can be found, relative to CATALINA_HOME. You’ll see more of tomcat-users.xml shortly.
Table 4-6 describes the attribute of the <ResourceParams> element.
Attribute | Description | Required? |
---|---|---|
name | The name of the resource that these parameters belong to. | Yes |
As shown in the previous example from server.xml, <ResourceParams> uses subelements to set the parameters for the resource. Table 4-7 describes these subelements.
Subelement | Description | Number |
---|---|---|
parameter | Represents a parameter of this resource. It has no attributes and the two subelements listed next. | 1 or more |
name | The name of the parameter. | 1 |
value | The value of the parameter. | 1 |
Tomcat 5.5 no longer uses the <ResourceParams> element. Instead, you provide the information with the <Resource> element’s attributes.
<Resource name="UserDatabase" auth="Container" type="org.apache.catalina.UserDatabase" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" pathname="conf/tomcat-users.xml" />
Note how the values here correspond to those previously and thus perform the same function.
Web applications running on your server may use common databases and as such will benefit from a JDBC data source. In fact, even if an application is the only one that uses a database, it will benefit from making it into a data source. This makes it easy for you as the administrator to change the underlying database without disturbing Web applications.
Another advantage of data sources is that Tomcat can use connection pooling with them, which means database connections can be recycled once they’ve finished executing. This in turn leads to improved performance. Tomcat uses the Jakarta Commons Database Connection Pool mechanism, which you can find in CATALINA_HOME/common/lib/commons-collections-2.1.1.jar, commons-dbcp-1.2.1.jar, and commons-pool-1.2.jar.
The first step to data source configuration is to place the required JDBC driver in CATALINA_HOME/common/lib. This will allow Tomcat to find and access this driver.
As you saw earlier, you can configure the JNDI resource factory using the <Resource> and <ResourceParams> elements. Listing 4-1 shows you a MySQL data source defined for the whole server. This instance of the database will be shared between all the Web applications running on the server. Note that you can also place this definition in context XML files, Tomcat 5.5’s default context.xml files, and Tomcat 5.0.x’s <DefaultContext> element.
Listing 4-1: Configuring a JDBC Data Source
<Server port="8005" shutdown="SHUTDOWN" debug="0"> <GlobalNamingResources> <Resource name="jdbc/CatalogDB" auth="SERVLET" type="javax.sql.DataSource"/> <ResourceParams name="jdbc/CatalogDB"> <parameter> <name>driverClassName</name> <value>com.mysql.jdbc.Driver</value> </parameter> <parameter> <name>url</name> <value>jdbc:mysql://localhost:3306/catalog</value> </parameter> </ResourceParams> </GlobalNamingResources>
This defines a data source called jdbc/CatalogDB and sets its drivers and connection URL. This illustrates how you could change the underlying database without affecting Web applications. In this case, the parameters shown in Table 4-8 are allowed.
Parameter | Description | Required? |
---|---|---|
driverClassName | Java class name of the JDBC driver. This driver should be placed in CATALINA_HOME/common/lib. | Yes |
logAbandoned | Determines whether Tomcat should log a stack trace of the code that abandoned a connection (see removeAbandoned). The default is false. | No |
maxActive | The maximum number of active connections in this pool. | No |
maxIdle | The maximum number of idle connections in this pool. | No |
maxWait | The time in milliseconds that the driver should wait for a connection before throwing an exception. | No |
user | The user ID used to log onto the database. | No |
password | The password used to log onto the database. | No |
removeAbandoned | Sets whether abandoned database connections are removed and recycled. An abandoned connection occurs if a Web application forgets to close it; if this situation continues, there will be no connections left in the pool. Removing and recycling connections avoids this situation. The default is false. | No |
removeAbandonedTimeout | The number of seconds that a connection has been idle before it’s classed as abandoned. The default is 300. | No |
url | The URL of the database server to be used. | Yes |
validationQuery | A SQL query used to validate a connection. The factory will perform this query and ensure that rows are returned before considering the connection valid. | No |
In addition to the previous configuration, the developer must declare the use of the resource in the application’s web.xml using a <resource-ref> element, as shown in Listing 4-2.
Listing 4-2: Configuring a Reference to a JDBC Data Source in web.xml
<?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"> <!-- Describe a DataSource --> <resource-ref> <description> Resource reference to a factory for java.sql.Connection instances that may be used for talking to a particular database that is configured in the tomcatBook.xml file. </description> <res-ref-name> jdbc/CatalogDB </res-ref-name> <res-type> javax.sql.DataSource </res-type> <res-auth> SERVLET </res-auth> </resource-ref> <!-- Define a Security Constraint on this Application --> <security-constraint> <web-resource-collection> <web-resource-name>Tomcat Book Application</web-resource-name> <url-pattern>/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>tomcat</role-name> </auth-constraint> <user-data-constraint> <description> Constrain the user data transport for the whole application </description> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint> <!-- Define the Login Configuration for this Application --> <login-config> <auth-method>FORM</auth-method> <realm-name>Tomcat Book Application</realm-name> <form-login-config> <form-login-page>/ch12/login.jsp</form-login-page> <form-error-page>/ch12/error.jsp</form-error-page> </form-login-config> </login-config> <!-- Security roles referenced by this web application --> <security-role> <description> The role that is required to log in to the Tomcat Book Application </description> <role-name>tomcat</role-name> </security-role> </web-app>
JavaMail is a standard programming API that can be used to create and send e-mails. Tomcat supports JavaMail by allowing you to configure a JavaMail session as a JNDI resource. Web applications can then use JNDI to look up and use this session.
You can configure JavaMail sessions that Web applications can use much in the same way as you can configure JDBC data sources. The theory and practice in both configurations are similar. In the case of JavaMail sessions, the Web application obtains a reference to the mail session without needing to know about the underlying implementation. Again, this allows you to change the underlying mail server without compromising any Web applications.
As already mentioned, the process of setting up a JavaMail session is analogous to setting up a JDBC data source. First, you must place the JavaMail API in CATALINA_HOME/common/lib so that Tomcat and Web applications can use its classes. It’s available from http://java.sun.com/products/javamail/downloads/ as mail.jar.
Second, configure the mail session in server.xml as shown in Listing 4-3.
Listing 4-3: Configuring a Mail Session
<Resource name="mail/Session" auth="Container" type="javax.mail.Session"/> <ResourceParams name="mail/Session"> <parameter> <name>mail.smtp.host</name> <value>localhost</value> </parameter> </ResourceParams>
By convention, you configure mail sessions to resolve to the mail subcontext. The snippet in Listing 4-3 configures the mail/Session context, which refers to an SMTP server running on localhost. You can modify the SMTP port (if it isn’t at the standard port 25) by setting the mail.smtp.port parameter.
Finally, set the JNDI resource in web.xml. Listing 4-4 shows the mail/Session reference.
Listing 4-4: Configuring a Reference to a JavaMail Session in web.xml
<resource-ref> <res-ref-name>mail/Session</res-ref-name> <res-type>javax.mail.Session</res-type> <res-auth>Container</res-auth> </resource-ref>
A service component groups together all the connectors that may be used with an engine.
<Service name="Catalina">
This service is called Catalina. This name will be visible in logs and error messages, clearly identifying the component. Service management software can also use it to identify the service instance.
Table 4-9 describes the attributes of the <Service> element.
Attribute | Description | Required? |
---|---|---|
className | The Java class name for the service class to use. The default is org.apache.catalina.core.StandardService. | No |
debug | Tomcat 5.0.x only. The level of debugging for this service. The levels are 1 (errors), 2 (warnings), 3 (information), and 4 (debug). These correspond to the levels of debugging in the logger component. | No |
This attribute applies to the standard implementation (see className next). It may not exist if another implementation is used. | ||
The default is zero, meaning no debugging (though the associated logger will still log fatal messages). | ||
name | The service name, used in logging and management. If more than one <Service> element appears inside the <Server> element, you must make sure their name attributes are different. | Yes |
Table 4-10 describes the subelements that a <Service> element can have.
Subelement | Description | Number |
---|---|---|
Connector | Connects Tomcat to request, either from users or from another Web server. | 1 or more |
Engine | This is Tomcat’s request-processing machinery. | 1 |
The following are the two connection points where a request enters Tomcat:
From a front-end Web server, which could be Apache, IIS, or any other Web server
From a Web browser
One way to handle these connection requirements is to create a customized version of Tomcat for each situation. This is inefficient and hard to maintain. This is where connectors come in: a connector adapts an engine to the outside world by passing requests into the engine and passing responses out to the user. The connector handles the protocol, connection conventions, and so on, so that the engine doesn’t have to handle them.
You can associate more than one connector with a single engine. For example, you may want to provide an HTTP service and an HTTPS service to your users from the same server. In this case, you configure an HTTP connector and an SSL connector in the same engine. You’ll see more on this in Chapter 9. For the meantime, let’s look through server.xml and see the default settings.
A number of different options are available to you when you configure a connector. server.xml shows four of the most common.
An HTTP connector
An SSL connector
An AJP 1.3 connector for connecting to another Web server
A proxy connector
The default connector for the Catalina engine is an HTTP/1.1 connector.
<!-- Define a non-SSL Coyote HTTP/1.1 Connector on port 8080 --> <Connector port="8080" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" debug="0" connectionTimeout="20000" disableUploadTimeout="true" />
This sets a connector to listen on port 8080 for HTTP requests. Table 4-11 describes the attributes that are common to all connectors, and Table 4-12 describes the HTTP connector’s attributes after the descriptions of the other <Connector> elements in server.xml.
Attribute | Description | Required? |
---|---|---|
address | For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server. | No |
allowTrace | A Boolean value that enables or disables the TRACE HTTP method (which prompts the server to return a copy of the request back to the client for inspection). The default is false. | No |
enableLookups | Sets whether the DNS hostname of the client can be looked up. false skips the DNS lookup and returns the IP address as a string (thereby improving performance). The default is true. | No |
maxPostSize | The maximum size in bytes of a POST request. You can disable this by setting this attribute to a value less than or equal to zero. The default is 2097152 (2 megabytes). | No |
redirectPort | If this connector supports non-SSL requests and a request is received that requires SSL transport, Tomcat will automatically redirect the request to the port number specified here. | No |
scheme | The name of the protocol you want to use for this connector. For example, you’d set this attribute to https for an SSL connector. The default is http. | No |
secure | If you want to have calls to request.isSecure() return true (which is the case for an SSL connector), set this to true. The default is false. | No |
URIEncoding | The character encoding to use to decode the URI bytes. The default is ISO-8859-1. | No |
useBodyEncodingForURI | This specifies if the encoding specified in contentType should be used for URI query parameters, instead of using the URIEncoding. This setting is for compatibility with Tomcat 4.1.x, where the encoding specified in the contentType was also used for the parameters from the URL. The default is false. | No |
Attribute | Description | Required? |
---|---|---|
acceptCount | The maximum queue length for incoming connection requests when all possible request-processing threads are in use. Any requests received when the queue is full will be refused. The default is 10. | No |
bufferSize | The size (in bytes) of the buffer to be provided for input streams created by this connector. The default is 2048. | No |
compressableMimeTypes | The value is a comma-separated list of MIME types for which HTTP compression may be used. The default is text/html,text/xml,text/plain. | No |
compression | The connector may use HTTP/1.1 GZIP compression in an attempt to save server bandwidth. The acceptable values for the parameter are off (disables compression), on (allows compression, which causes text data to be compressed), force (forces compression in all cases), or an integer (which is equivalent to on but specifies the minimum amount of data before the output is compressed). If the content length isn’t known and compression is set to on or more aggressive, the output will also be compressed. The default is off. | No |
connectionLinger | The number of milliseconds during which the sockets used by this connector will linger when they are closed. The default is -1 (socket linger is disabled). | No |
connectionTimeout | The number of milliseconds this connector will wait, after accepting a connection, for the request URI line to be presented. The default is 60000 (that is, 60 seconds). | No |
debug | Tomcat 5.0.x only. The debugging level for log messages generated by this component. The levels are 1 (errors), 2 (warnings), 3 (information), and 4 (debug). These correspond to the levels of debugging in the logger component. The default is zero, meaning no debugging (though the associated logger will still log fatal messages). | No |
disableUploadTimeout | Used to set a connection timeout while a servlet is being executed. This gives the servlet longer to complete its execution or allows a longer timeout during data upload. The default is false. | No |
maxHttpHeaderSize | The maximum size of the request and response HTTP header, specified in bytes. The default is 4096. | No |
maxKeepAliveRequests | The maximum number of HTTP requests that can be maintained until Tomcat closes the connection. A setting of 1 will disable HTTP/1.0 and HTTP/1.1 keep-alive and pipelining. A setting of -1 will allow an unlimited amount of pipelined or keep-alive HTTP requests. The default is 100. | No |
maxSpareThreads | The maximum number of unused request-processing threads that will be allowed to exist until the thread pool stops the unnecessary threads. The default is 50. | No |
maxThreads | The maximum number of request-processing threads to be created, which therefore determines the maximum number of simultaneous requests that can be handled. The default is 200. | No |
minSpareThreads | The number of request-processing threads created when this connector starts. The connector will also make sure it has the specified number of idle processing threads available. This attribute should be set to a value smaller than maxThreads. The default is 4. | No |
noCompressionUserAgents | A comma-separated list of regular expressions matching HTTP user-agents for which compression should not be used. The default is an empty string. | No |
port | The port on which this connector will create a server socket and await incoming connections. Only one application may listen to a particular port number on a particular IP address. | Yes |
protocol | Must be HTTP/1.1 to use the HTTP handler, which is the default. | No |
proxyName | If this connector is being used in a proxy configuration, configure this attribute to specify the server name to be returned for calls to request.getServerName(). | No |
proxyPort | If this connector is being used in a proxy configuration, configure this attribute to specify the server port to be returned for calls to request.getServerPort(). | No |
restrictedUserAgents | A comma-separated list of regular expressions matching HTTP user-agents for which HTTP/1.1 or HTTP/1.0 keep-alive should not be used, even if they advertise support for these features. The default is an empty string. | No |
server | Tomcat 5.5 only. The Server header for the HTTP response. | No |
strategy | Tomcat 5.5 only. The thread-pooling strategy to be used. The default strategy doesn’t use a master thread. However, you can use a more conventional strategy with a master listener thread by setting this attribute’s value to ms. The master strategy will work significantly better if you also use the threadPriority attribute, which will apply only to the thread that listens on the server socket. The default is lf. | No |
socketBuffer | The size (in bytes) of the buffer to be provided for socket output buffering. A setting of -1 disables the use of a buffer. The default is 9000. | No |
tcpNoDelay | If set to true, the TCP_NO_DELAY option will be set on the server socket, which improves performance under most circumstances. The default is true. | No |
threadPriority | The priority of the request-processing threads within the JVM. The default is java.lang.Thread#NORM_PRIORITY. See the documentation for the java.lang.Thread class for more details on what this priority means. | No |
<!-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 --> <!-- <Connector port="8443" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" disableUploadTimeout="true" acceptCount="100" debug="0" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" /> -->
This sets a secure SSL connector to listen on port 8443 for HTTPS requests. It shares all the attributes of an ordinary HTTP connector but has some unique SSL attributes all its own. Table 4-13 describes these.
Attribute | Description | Required? |
---|---|---|
algorithm | The certificate algorithm to be used. The default is SunX509. | No |
clientAuth | Set to true if you require a valid certificate chain from the client before accepting a connection. false won’t require a certificate chain unless the client requests a resource protected by a security constraint that uses CLIENT-CERT authentication. The default is false. | No |
keystoreFile | The path to the keystore file where you have stored the server certificate to be loaded. The default is .keystore in the home directory of the user that’s running Tomcat. | No |
keystorePass | The password used to access the server certificate from the specified keystore file. The default is changeit. | No |
keystoreType | The type of keystore file to be used for the server certificate. The default is JKS. | No |
sslProtocol | The version of the SSL protocol to use. The default is TLS. | No |
ciphers | A comma-separated list of the encryption ciphers that may be used. Any available cipher may be used by default. | No |
<!-- Define a Coyote/JK2 AJP 1.3 Connector on port 8009 --> <Connector port="8009" enableLookups="false" redirectPort="8443" debug="0" protocol="AJP/1.3" />
This sets up an AJP 1.3 connector listening on port 8009. This type of connector allows Tomcat to connect to an Apache Web server to provide JSP pages and servlets while Apache provides HTML pages and important user-management functionality. Table 4-14 describes the AJP connector’s attributes.
Attribute | Description | Required? |
---|---|---|
debug | Tomcat 5.0.x only. The debugging detail level of log messages generated by this component. The levels are 1 (errors), 2 (warnings), 3 (information), and 4 (debug). These correspond to the levels of debugging in the logger component. The default is zero, meaning no debugging (though the associated logger will still log fatal messages). | No |
protocol | Must be AJP/1.3 to use the AJP handler. | Yes |
<!-- Define a Proxied HTTP/1.1 Connector on port 8082 --> <!-- See proxy documentation for more information about using this. --> <!-- <Connector port="8082" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" acceptCount="100" debug="0" connectionTimeout="20000" proxyPort="80" disableUploadTimeout="true" /> -->
The final connector setup in server.xml configures a connector to work with a proxy server. This allows the proxy to provide a firewall.
All these connectors are configured to automatically send errors and logging information to the logger associated with their engine.
As promised, Table 4-11 describes the common attributes that are shared by all the connectors described previously.
The default HTTP connector has the attributes described in Table 4-12.
An SSL connector has a number of unique attributes, as described in Table 4-13.
The final set of attributes belongs to the AJP connector and is described in Table 4-14. Remember that this connector also has the common attributes described in Table 4-11.
You can have as many connectors as you need in a service to handle the different connection requirements for a server, but you can have only one engine. An engine executes Web applications when processing incoming requests and generating outgoing responses.
<!-- Define the top level container in our container hierarchy --> <Engine name="Catalina" defaultHost="localhost" debug="0">
An engine represents a running instance of the servlet processor; in other words, it’s the servlet engine. The default engine in server.xml is called Catalina. The defaultHost is the host component to which this engine will direct a request if it’s not for a known host on this server. The debug attribute here specifies that there will be no debug messages for this engine written by the logger to the log.
Table 4-15 describes the attributes of the <Engine> element.
Attribute | Description | Required? |
---|---|---|
backgroundProcessorDelay | Represents the delay in seconds between the invocation of the backgroundProcess() method on this engine and its child containers, including all hosts and contexts. Child containers will be invoked if their delay value is negative (which would mean they’re using their own processing thread). Setting this to a positive value will cause a thread to be spawned. After waiting the specified amount of time, the thread will invoke the backgroundProcess() method on this engine and all its child containers. The default is 10. | No |
className | Class name of the implementation to use. The default is org.apache.catalina.core.StandardEngine. | No |
debug | Tomcat 5.0.x only. The level of debugging for this engine. The levels are 1 (errors), 2 (warnings), 3 (information), and 4 (debug). These correspond to the levels of debugging in the logger component. | No |
This is an attribute of the standard implementation and may change if you’re using another implementation. | ||
The default is zero, meaning no debugging (though the associated logger will still log fatal messages). | ||
defaultHost | The default hostname. This host will process requests directed to host names on this server but that aren’t configured in server.xml. This name must match the name of one of the host elements nested in this engine. | Yes |
jvmRoute | The identifier that must be used in load balancing to enable session affinity. This value must be unique across all Tomcat 5 servers that participate in the cluster. It will be appended to the generated session identifier, therefore allowing the front-end proxy to forward a particular session to the same Tomcat 5 instance. | No |
name | Name of this engine, used in log and error messages. | Yes |
The <Engine> element has the subelements described in Table 4-16.
Subelement | Description | Number |
---|---|---|
DefaultContext | Tomcat 5.0.x only. Creates a default context for Web applications that are automatically deployed when Tomcat starts. Its settings are a subset of a context’s, so it will be covered in the next chapter. Tomcat 5.5 uses an external default context file. | 0 or 1 |
Logger | Tomcat 5.0.x only. The logging component instance used by this engine for logging messages. Unless overridden by inner containers, this is the default logger instance for any nested components inside the engine. | 0 or 1 |
Realm | The user-authentication realm used by Tomcat’s declarative security support. | 0 or 1 |
Host | Each <Host> element is a virtual host handled by this engine. Tomcat can handle multiple virtual hosts per engine instance. | 1 or more |
Listener | Lifecycle listeners monitor the starting and stopping of the engine. You’ll see one use for listeners in Chapter 9. | 0 or more |
Valve | Valves add processing logic into the request- and response-handling pipeline at the engine level. Standard valves are used to perform access logging, request filtering, implementing single sign-on, and so on. | 0 or more |
The first subelement inside the <Engine> is the default logger.
<!-- Global logger unless overridden at lower levels --> <Logger className="org.apache.catalina.logger.FileLogger" prefix="catalina_log." suffix=".txt" timestamp="true"/>
A logger is a nested component that collects log information (debug or error messages) from Tomcat and Web application code and writes it to log files. Log files are placed in the CATALINA_HOME/logs directory by default. You can change this location with the directory attribute.
The default configuration uses the standard FileLogger class and configures the log name to be of the form catalina_log.DATE.txt.
More than one kind of logger exists, but all <Logger> elements have common attributes, as described in Table 4-17.
Attribute | Description | Required? |
---|---|---|
className | The Java class to use for this instance of the logger. | Yes |
verbosity | The level of logging are as follows: 0: Fatal messages only 1: Error messages 2: Warning messages 3: Information messages 4: Debug information The numbers are cumulative. (That is, 4 logs all messages, 3 logs everything but debug information, and so on.) The default is 1. | No |
As you can see from Table 4-17, the <Logger> element must specify a className attribute. You use this attribute to choose the standard logger implementation for this component. The className attribute can contain one of the classes shown in Table 4-18.
Class Name | Description |
---|---|
org.apache.catalina.logger.FileLogger | Logs to a file |
org.apache.catalina.logger.SystemErrLogger | Logs to the standard error stream. |
org.apache.catalina.logger.SystemOutLogger | Logs to the standard output stream |
The only one of these loggers that has any attributes is org.apache.catalina.logger.FileLogger. Table 4-19 describes these attributes.
Attribute | Description | Required? |
---|---|---|
directory | The location of the log files. You may use relative or absolute paths. Relative paths are interpreted in relation to CATALINA_HOME. The default is CATALINA_HOME/logs. | No |
prefix | The prefix for the log filenames. The default is catalina. | No |
suffix | A suffix for the log filenames. The default is .log. | No |
timestamp | Set to true to add a date and time stamp to each filename. Best practice dictates that you add a time stamp to your log files. The default is false. | No |
Although this is a perfectly adequate logging mechanism, you can also configure Tomcat 5.0.x to use Log4J as described next. This is a much more powerful and flexible mechanism, so you may be tempted.
Tomcat 5.5 doesn’t include the logger component and relies instead on the Jakarta Commons logging mechanism. This mechanism is a thin bridge between logging libraries and allows you to use any logging toolkit you want. The two most common are the Java 1.4 (and onward) built-in logging feature and the Apache Log4J toolkit. It’s the latter that’s most often used with Tomcat, so it’s the one described in this section.
The first step is to download the Log4J classes from http://logging.apache.org/log4j/. Tomcat 5.5 uses the Commons logging mechanism during bootup, so if you want to use Log4J to harness the commons logging messages, you must also include it at bootup. To do this, add the log4j.jar binary to the boot classpath in the catalina.bat/catalina.sh script.
rem catalina.bat set CLASSPATH=%CLASSPATH%; %CATALINA_HOME%\bin\bootstrap.jar; %CATALINA_HOME%\bin\log4j.jar # catalina.sh CLASSPATH="$CLASSPATH": "$CATALINA_HOME"/bin/bootstrap.jar: "$CATALINA_HOME"/bin/commons-logging-api.jar: "$CATALINA_HOME"/bin/log4j.jar
Change the path to your Log4J binary.
The version of the Commons logging that Tomcat uses when booting up is a stripped-down version for simple logging to the console (CATALINA_HOME/bin/commons-logging-api.jar). Log4J, on the other hand, uses the full functionality of the logging mechanism. This means you must download the full distribution from http://jakarta.apache.org/commons/logging/. Copy the commons-logging.jar file to CATALINA_HOME/common/lib, where Tomcat, user applications, and Log4J can see it.
You can’t replace the stripped-down version of the logging API in the bin directory directly. The steps described previously will carry out this task during bootup.
Note | If you’re using Tomcat 5.0.x, you don’t need to do any of this. However, you need to copy log4j.jar to CATALINA_HOME/common/lib. Also remember to remove any <Logger> elements in server.xml. |
The final step of configuration is to add a Log4J configuration file as shown in Listing 4-5. Call this file log4j.properties, and place it in CATALINA_HOME/common/classes. This places it in the same scope as the rest of the logging mechanism.
Listing 4-5: CATALINA_HOME/common/classes/log4j.properties
# Set the root logger for Tomcat log4j.rootLogger=INFO, Tomcat # Log to a file log4j.appender.Tomcat=org.apache.log4j.FileAppender log4j.appender.Tomcat.File=C:/jakarta-tomcat-5.5.3/logs/tomcat.log # Use the simple layout log4j.appender.Tomcat.layout=org.apache.log4j.SimpleLayout
This is a simple configuration that sets the level of logging and the log file for Tomcat to use. The logging levels are, in ascending order of severity, as follows: ALL, DEBUG, INFO, WARN, ERROR, FATAL, and OFF. Be careful and set logging to only the level you require because there can be severe performance penalties if you choose too low a level; at the same time, you may miss crucial information if you set the level too high.
Start Tomcat, and open the log file you configured previously. You should see the usual Tomcat startup messages, as shown in Listing 4-6.
Listing 4-6: The Log Messages from tomcat.log
INFO - Initializing Coyote HTTP/1.1 on http-8080 INFO - Initialization processed in 3004 ms INFO - Starting service Catalina INFO - Starting Servlet Engine: Apache Tomcat/5.5.3 INFO - XML validation disabled INFO - org.apache.webapp.balancer.BalancerFilter: init(): ruleChain: [org.apache.webapp.balancer.RuleChain: [org.apache.webapp.balancer.rules.URLStringMatchRule: Target string: News / Redirect URL: http://www.cnn.com], [org.apache.webapp.balancer.rules.RequestParameterRule: Target param name: paramName / Target param value: paramValue / Redirect URL: http://www.yahoo.com], [org.apache.webapp.balancer.rules.AcceptEverythingRule: Redirect URL: http://jakarta.apache.org]] INFO - ContextListener: contextInitialized() INFO - SessionListener: contextInitialized() INFO - ContextListener: contextInitialized() INFO - SessionListener: contextInitialized() INFO - Starting Coyote HTTP/1.1 on http-8080 INFO - JK2: ajp13 listening on /0.0.0.0:8009 INFO - Jk running ID=0 time=0/101 config=C:\jakarta-tomcat-5.5.3\conf\jk2.properties INFO - Server startup in 5789 ms
If you had set the debug level higher than INFO, then there will be no messages in the log file.
You aren’t limited to using the simple text file. For example, the previous listing has no dates or times. To change this, you can use a pattern layout, which uses pattern characters just as C does. Table 4-20 describes those characters relevant to Tomcat logging. See http://logging.apache.org/log4j/docs/api/org/apache/log4j/PatternLayout.html for more details on Log4J’s logging patterns.
Pattern Character | Description |
---|---|
c | The category of the logging event. In Tomcat terms, this displays the component that made the log entry. You can configure the precision of the category name by placing an integer in brackets after the character. In this case, only the corresponding number of rightmost components of the category name will be printed. For example, for the category log4j.logger.org.apache.catalina.core.ContainerBase, the pattern %c{1} will print ContainerBase. This is a useful pattern character when you want to find out from where a certain log message has come. |
d | The date of this log entry, which may be followed by a date format enclosed between braces—for example, %d{HH:mm:ss} or %d{dd MMM yyyy HH:mm:ss}. If no format is given, then ISO8601 format is used. For better results you should use the Log4J date formatters. These are ABSOLUTE, DATE, and ISO8601, for specifying AbsoluteTimeDateFormat, DateTimeDateFormat, and ISO8601DateFormat, respectively—for example, %d{ISO8601} or %d{ABSOLUTE}. ABSOLUTE is HH:mm:ss,SSS. DATE is dd MMM YYYY HH:mm:ss,SSS. ISO8601 is YYYY-MM-dd HH:mm:ss,SSS. |
F | The filename where the logging request was issued. This can be slow, so you should avoid using this option unless execution speed isn’t an issue. |
l | The location of the caller that generated the logging event. The location information depends on the JVM implementation but usually consists of the fully qualified name of the calling method, followed by the filename and line number between parentheses. Here’s an example: org.apache.jk.server.JkMain.start(JkMain.java:355). The location information can be useful, but obtaining it is extremely slow. |
L | The line number where the logging request was issued. Obtaining caller location information is extremely slow. |
m | The application-supplied message associated with the logging event. |
M | The method name where the logging request was issued. Obtaining caller location information is extremely slow. |
n | The platform-dependent line separator character or characters. This conversion character offers practically the same performance as using nonportable line separator strings such as \n or \r\n. Thus, it’s the preferred way of specifying a line separator. |
p | Used to output the priority of the logging event. |
r | Used to output the number of milliseconds elapsed since the start of the application until the creation of the logging event. |
t | Used to output the name of the thread that generated the logging event. |
% | The sequence %% outputs a single percent sign. |
Listing 4-7 shows how to put these characters into action.
Listing 4-7: CATALINA_HOME/common/classes/log4j.properties
# Set the root logger for Tomcat log4j.rootLogger=INFO, Tomcat # Log to a pattern file log4j.appender.Tomcat=org.apache.log4j.FileAppender log4j.appender.Tomcat.File=C:/jakarta-tomcat-5.5.3/logs/tomcat.pattern.log # Use a pattern layout log4j.appender.Tomcat.layout=org.apache.log4j.PatternLayout log4j.appender.Tomcat.layout.ConversionPattern=%d{ISO8601} : %p : %m %n
In this case, you’re logging the date in ISO8601 format, followed by the priority of the message (%p) and message itself (%m). The line is ended with a newline character (%n). Start Tomcat, and examine tomcat.pattern.log. It should look something like Listing 4-8.
Listing 4-8: tomcat.pattern.log
2004-10-03 20:50:19,527 : INFO : Initializing Coyote HTTP/1.1 on http-8080 2004-10-03 20:50:19,617 : INFO : Initialization processed in 2293 ms 2004-10-03 20:50:20,128 : INFO : Starting service Catalina 2004-10-03 20:50:20,138 : INFO : Starting Servlet Engine: Apache Tomcat/5.5.3 2004-10-03 20:50:20,168 : INFO : XML validation disabled 2004-10-03 20:50:22,562 : INFO : org.apache.webapp.balancer.BalancerFilter: init(): ruleChain: [org.apache.webapp.balancer.RuleChain: [org.apache.webapp.balancer.rules.URLStringMatchRule: Target string: News / Redirect URL: http://www.cnn.com], [org.apache.webapp.balancer.rules.RequestParameterRule: Target param name: paramName / Target param value: paramValue / Redirect URL: http://www.yahoo.com], [org.apache.webapp.balancer.rules.AcceptEverythingRule: Redirect URL: http://jakarta.apache.org]] 2004-10-03 20:50:22,942 : INFO : ContextListener: contextInitialized() 2004-10-03 20:50:22,942 : INFO : SessionListener: contextInitialized() 2004-10-03 20:50:23,773 : INFO : ContextListener: contextInitialized() 2004-10-03 20:50:23,773 : INFO : SessionListener: contextInitialized() 2004-10-03 20:50:24,504 : INFO : Starting Coyote HTTP/1.1 on http-8080 2004-10-03 20:50:25,115 : INFO : JK2: ajp13 listening on /0.0.0.0:8009 2004-10-03 20:50:25,135 : INFO : Jk running ID=0 time=0/90 config=C:\jakarta-tomcat-5.5.3\conf\jk2.properties 2004-10-03 20:50:25,215 : INFO : Server startup in 5598 ms
Here you can see the pattern has been applied to each of the log entries.
If you want, you can also output to HTML. Listing 4-9 shows this configuration.
Listing 4-9: CATALINA_HOME/common/classes/log4j.properties
# Set the root logger for Tomcat log4j.rootLogger=INFO, Tomcat # Log to an HTML file log4j.appender.Tomcat=org.apache.log4j.FileAppender log4j.appender.Tomcat.File=C:/jakarta-tomcat-5.5.3/logs/tomcat.log.html # Set the layout to HTML and specify a title log4j.appender.Tomcat.layout=org.apache.log4j.HTMLLayout log4j.appender.Tomcat.layout.Title=Apress Tomcat Log
Figure 4-2 shows the results.
Figure 4-2: The HTML layout log
If you want to log to the console window, you have two choices: don’t use Log4J and rely on the default logging or use the console logger from Log4J. The advantage of using Log4J is that you can use custom layouts and change the level of the logging threshold. Listing 4-10 shows how to log to the console.
Listing 4-10: CATALINA_HOME/common/classes/log4j.properties
# Set the root logger for Tomcat log4j.rootLogger=INFO, Tomcat # Log to the console log4j.appender.Tomcat=org.apache.log4j.ConsoleAppender log4j.appender.Tomcat.Target=System.out # Set a custom layout level log4j.appender.Tomcat.layout=org.apache.log4j.PatternLayout log4j.appender.Tomcat.layout.ConversionPattern=%d{ISO8601} : %p : %m %n
The pattern here is the same as that for the pattern layout file, so the output to the console will be identical.
Now that you know how to log to different media, you can send different levels of messages to different destinations. In the example shown in Listing 4-11, all messages of level INFO and higher are logged to a file, and those of ERROR and higher are logged to the console for immediate attention.
Listing 4-11: CATALINA_HOME/common/classes/log4j.properties
# Send all INFO messages and above to a file and # all ERROR messages and above to the console log4j.rootLogger=INFO, TomcatINFO, TomcatERROR # Use a pattern file for the INFO messages log4j.appender.TomcatINFO=org.apache.log4j.FileAppender log4j.appender.TomcatINFO.File=C:/jakarta-tomcat-5.5.3/logs/tomcat.pattern.log log4j.appender.TomcatINFO.layout=org.apache.log4j.PatternLayout log4j.appender.TomcatINFO.layout.ConversionPattern=%d{ISO8601} : %p : %m %n # Use the console for ERROR messages 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
You can use a huge number of variations with Log4J, such as using the Windows system log and Unix syslog, though such exhaustive treatment is beyond the scope of this chapter.
So far you’ve seen how to log Tomcat’s log messages, no matter where they originated, to one or more destinations. However, you may want to log messages from different locations to different files. For example, in previous versions of Tomcat, you could place loggers at each component level to log to different log files. This meant you could see what was occurring in each component. To replicate this, you must assign a component’s Log4J logger (different from a logger component of old) to an appender. The configuration is then the same as previously.
To assign a logger to an appender, use the following convention:
log4j.logger.LOGGER_NAME=[LOGGING_LEVEL],APPENDER_NAME
The LOGGER_NAME is usually the fully qualified class name of the component you want to log, with the exception of engines, hosts, and contexts. The following is an example of the tomcatBook context’s logger, assuming it’s in the Catalina engine and the localhost host:
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/tomcatBook]
Putting all this together, the following will assign the tomcatBook context’s log messages to the tomcatBook appender with a default debug level of INFO:
log4j.logger.org.apache.catalina.core.ContainerBase. [Catalina].[localhost].[/tomcatBook]=INFO,tomcatBook
Listing 4-12 shows a log4j.properties file that sets a master log file that will log everything and a context-specific log file that logs only messages to that context.
Listing 4-12: A log4j.properties That Logs Context-Specific Messages
# Set the root logger for Tomcat log4j.rootLogger=INFO, Tomcat # Log to a file log4j.appender.Tomcat=org.apache.log4j.FileAppender log4j.appender.Tomcat.File=C:/jakarta-tomcat-5.5.3/logs/tomcat.log # Use the simple layout log4j.appender.Tomcat.layout=org.apache.log4j.SimpleLayout log4j.logger.org.apache.catalina.core.ContainerBase. [Catalina].[localhost].[/tomcatBook]=INFO,tomcatBook # Log to a file log4j.appender.tomcatBook=org.apache.log4j.FileAppender log4j.appender.tomcatBook.File=C:/jakarta-tomcat-5.5.3/logs/tomcatBook.log # Use the pattern layout log4j.appender.tomcatBook.layout=org.apache.log4j.PatternLayout log4j.appender.tomcatBook.layout.ConversionPattern=%c{3}: %m %n
The tomcatBook appender will display the last three sections of the component that created the log message, followed by the message. Here’s an example log message in CATALINA_HOME/logs/tomcatBook.log:
[Catalina].[localhost].[/tomcatBook]: REQUEST URI=/tomcatBook/
You can configure other components in the same way. Appendix A contains details of Tomcat’s Log4J loggers for your reference.
The one slight drawback of this approach is that you repeat the logging activity if you set the same levels of logging for the two log files. In the previous example, all messages on the server of level INFO and higher, including those for the tomcatBook context, are logged to the tomcat.log file. The logging messages from the tomcatBook context are also logged to the tomcatBook.log file, which means your server will be working hard to log double the amount of log messages for that context.
One solution is to reserve a serverwide log file for serious log messages, perhaps of level ERROR and higher, and have a log file for each context with INFO messages. Of course, you may not even need this level of logging for all your contexts once they’re deployed.
The next entry in server.xml is a realm, which is used for user authentication.
<!-- Because this Realm is here, an instance will be shared globally --> <!-- This Realm uses the UserDatabase configured in the global JNDI resources under the key "UserDatabase". Any edits that are performed against this UserDatabase are immediately available for use by the Realm. --> <Realm className="org.apache.catalina.realm.UserDatabaseRealm" debug="0" resourceName="UserDatabase"/>
Note that this realm uses the global resource you looked at earlier in the “Configuring a Global Resource” section. This realm is therefore attaching the global resource to the engine in which it resides.
Tomcat uses realms to perform authentication and implement container-managed security. They map usernames to passwords (for authentication) and usernames to user roles (for container-managed security). This means that Tomcat can then determine that users are who they say they are, using authentication, and determine which areas of the server are available to them, using container-managed security.
The user database is only one implementation of a realm. Others are data source realm, JDBC realm, JNDI realm, and JAAS realm. Tomcat 5 supports the memory realm for backward compatibility with Tomcat 4, but it’s inefficient and insecure, so you shouldn’t use it.
The various realms are described briefly next but will be dealt with in more detail in Chapter 11.
The user database realm is an upgraded version of the memory realm and is backward compatible with the memory realm. It comes with the same caveats as the memory realm.
Data source realms use JDBC data sources stored with JNDI names to authenticate users. This allows you to change the underlying storage mechanism without having to change the settings on your realms.
JDBC realms access relational databases to obtain authentication information. You can use any source of data that can be accessed with JDBC. This includes ODBC sources, such as Excel or comma-separated files, accessed with the JDBC-ODBC bridge. server.xml has a number of example JDBC realms commented out. The following uses a MySQL database instead of a text file:
<!-- <Realm className="org.apache.catalina.realm.JDBCRealm" debug="99" driverName="org.gjt.mm.mysql.Driver" connectionURL="jdbc:mysql://localhost/authority" connectionName="test" connectionPassword="test" userTable="users" userNameCol="user_name" userCredCol="user_pass" userRoleTable="user_roles" roleNameCol="role_name" /> -->
You can configure a JNDI LDAP service provider to provide user information from an existing directory service. This would allow you to use employee information that’s already available.
You can use the JAAS realm to authenticate users using the Java Authentication and Authorization Service (JAAS). This allows you to use any authentication mechanism you choose, but you have to write your own authentication module to implement whichever one you choose.
A host component represents a single virtual host running on this server.
<Host name="localhost" debug="0" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
This virtual host is localhost. The applications running in this host are located in the CATALINA_HOME/webapps directory.
The unpackWARs attribute tells Tomcat to unpack any packaged WAR files found in the appBase directory if it’s set to true. A value of false means that Tomcat will execute the Web applications without unpacking them, which saves space but increases response time.
A <Host> element is a container and has the attributes described in Table 4-21. These are the attributes of all hosts, and custom implementations of hosts are possible.
Attribute | Description | Required |
---|---|---|
appBase | The base directory for this virtual host. This is a directory that may contain Web applications to be deployed on this virtual host. You may specify an absolute pathname or a pathname relative to the CATALINA_HOME directory. | Yes |
autoDeploy | This flag value indicates whether new Web applications added to the appBase directory while Tomcat is running should be deployed automatically. The default is true. | No |
background-ProcessorDelay | The delay in seconds between the invocation of the backgroundProcess() method on this host and its child containers, including all contexts. Child containers will be invoked if their delay value is negative (which would mean they’re using their own processing thread). A positive value will cause a thread to be spawned. After waiting the specified amount of time, the thread will invoke the backgroundProcess() method on this host and all its child containers. A host will use background processing to perform live Web application deployment–related tasks. The default is -1, which means the host will rely on the background-processing thread of its parent engine. | Yes |
className | Class name of the implementation to use. The default is org.apache.catalina.core.StandardHost. | No |
deployOnStartup | Set to true to automatically deploy Web applications on startup. The default is true. | No |
name | The name of this virtual host, as configured with DNS. One of the hosts nested within an engine must have a name that matches the defaultHost attribute of that engine. | Yes |
In addition, the standard host has the attributes defined in Table 4-22.
Attribute | Description | Required |
---|---|---|
debug | Tomcat 5.0.x only. The level of debugging logged by the associated logger. The levels are 1 (errors), 2 (warnings), 3 (information), and 4 (debug). These correspond to the levels of debugging in the logger component. The default is zero, meaning no debugging (though the associated logger will still log fatal messages). | No |
deployXML | false disables the ability to deploy applications using an XML configuration file. This also prohibits the manager application from deploying Web application directories or WAR files that aren’t located in CATALINA_HOME/conf/[Engine_name]/[Host_name]. XML-configured applications are deployed with Tomcat’s security permissions, so you should set this to false if untrustworthy users can manage Web applications. The default is true. | No |
errorReportValveClass | Class name of the error-reporting valve that will be used by this host. You can use this property to customize the look of the error pages that will be generated by Tomcat. The class must implement the org.apache.catalina.Valve interface. The default is org.apache.catalina.valves.ErrorReportValve. | No |
unpackWARs | Set to true if you want to unpack WAR files in the appBase directory into a corresponding directory structure. false tells Tomcat to run such Web applications directly from their WAR file. The default is true. | No |
workDir | A scratch directory to be used by applications running in this host. Each application will have its own directory with temporary read/write use. Configuring a working directory for a context will override this value. This directory is visible to servlets in the Web application as a servlet context attribute (of type java.io.File) named javax.servlet.context.tempdir as described in the Servlet specification. The default is a suitable directory underneath CATALINA_HOME/work. | No |
Table 4-23 describes the subelements that can be placed inside a <Host> element.
Subelement | Description | Number |
---|---|---|
Context | A context defines a Web application deployed within this host. When using Tomcat 5, you shouldn’t place any context entries in server.xml because server.xml isn’t reloaded after changes are made. Use XML configuration files or deployment tools, such as the manager application, instead. | 0 or more |
DefaultContext | Tomcat 5.0.x only. The default context is a set of property values for a Web application that’s deployed within this host but doesn’t have its own context specified. Typically, this default context is used for Web applications that are part of the standard behavior of the Tomcat server, and Web applications that are automatically deployed. Tomcat 5.5 uses external default context files. | 0 or 1 |
Logger | Tomcat 5.0.x only. A default logger that’s configured for this host. Overrides any previously specified logger. | 0 or 1 |
Realm | A realm that can be accessed across all the Web applications running within this host—unless a lower-level component specifies its own realm. | 0 or 1 |
Valve | You can add a valve to monitor access, filter requests, and implement single sign-on. | 0 or more |
Listener | You can add a listener to monitoring lifecycle events, such as this host starting or stopping, and to implement user Web applications. | 0 or more |
Alias | Defines an alias for this host if two or more network names need to apply to it. | 0 or more |
You’ll cover context configuration in Chapter 5 when you’ll learn how to configure Web applications.
A valve is a Tomcat-specific interception mechanism for catching requests and responses. Any requests destined for the localhost host will be passed through the valve defined here, if it were to be uncommented.
<!-- <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/> -->
The org.apache.catalina.valves.AccessLogValve valve creates access log files in the same format as Apache’s log file. The previous configuration will create log files, in the common format, in CATALINA_HOME/logs. They will be named in the form localhost_access_log.DATE.txt.
You can also install valves at the engine level. Any valve that’s installed at the engine level will have access to every request handled by the engine, regardless of which connector the request comes through. Therefore, you must test the valve thoroughly and make sure it doesn’t require a lot of processor time to complete its operation. The standard valves that come with Tomcat have been designed and tested for efficiency.
Note | Valves are specific to Tomcat and not part of the Servlet specification. Application programmers can use filters as a similar interception mechanism. They are part of the Servlet specification and reside within a Web application. |
You’ll see how to configure and use the standard valves in Chapter 7.
If a user has an object that needs to know about server lifecycle events, then they need to implement a listener. The basic listener configuration is as follows:
<Listener className="com.acme.listeners.Listener" />
The className attribute is required. You can add other attributes according to the properties of the class. They’re matched with the standard JavaBean naming mechanism.
If you need to map more than one network name to a single virtual host, then you need to configure an alias. For example, say you want to map www.company.com and www.company.org to the same host; you’d do the following:
<Host name="www.company.com" ...> <Alias>www.company.org</Alias> </Host>