servlet hosting logo
Contact us: +44 (0) 870 1657215 - contact@nameonthe.net
Members of
Members of Nominet Ripe member WorldPay Guarantee
We accept the following payment methods:
Visa payments supported by WorldPay Visa/Delta payments supported by WorldPay Visa/Electron payments supported by WorldPay Mastercard payments supported by WorldPay Switch payments supported by WorldPay JCB Solo payments supported by WorldPay
Tomcat Private JVM Account Quick Start Guide
*Note* If you don't have a Name On The Net Tomcat support can still be found here
A private JVM account has a dedicated Tomcat instance running within its own JVM. This presents the opportunity to use some of the more sophistiated configuration options which not available with a shared Tomcat instance. Examples include connection pooling, defining JNDI resources, specialised logging strategies, running Tomcat headless and using the Tomcat admin app. On account set-up your Tomcat instance will be pre-configured to a working state - which can be restored if subsequent modification of the configuration leaves your Tomcat instance inoperable. This guide presents a introduction to some of the more common account activities (configuration, deployment, viewing logs, etc) which will help you most productively use your private JVM account. If you require support or guidance with any other aspect of your account not covered here please contact support (support@nameonthe.net).
Logging in
The prerequisite to starting tomcat will be to log in into the server allocated to you. SSH is the mode of communication and is becoming a standard for performing remote administration of Unix servers replacing telnet which has severe security implications (SSH - Secure Shell). Ssh clients exist for virtually all platforms, modern Unix machines generally come with a ssh client pre-installed. If you are within a Wwindows environment a very popular ssh client is
putty which is free and is easy to configure with a small footprint. Once you have logged into the machine assigned to you (use the ip address/username/password triple to configure putty) you should see a prompt:

bash-2.05$

Shell Primer (if familiar with unix shells please skip)
For those familiar with DOS the Unix shell (DOS being the Windows nearest 'counterpart')* bears a strong similarity in that it is command line based application. However, the unix shell (or available shells to be precise) offers enormous power to the initiated without DOS's inherent limitations. An important difference is the path separators are '/'s rather than '\'s within Unix. To move around the filesystem and understanding where you currently are within it, you can use the following commands: cd (change directory),pwd (print working directory), ls (list contents of directory). To send the command to the server the carriage return key is always used.
Using the mysql command line client
The private JVM account comes with the mysql client pre-installed which allows you to carry out database maintenance tasks. In supplement to the database web interface the mysql command line client is used to perform more complex tasks that cannot be made via the web interface such as imported and dumping data. To connect to the client once logged in (see above) use the following command:mysql You should see the mysql client introduce itself as shown below:
bash-2.05$ mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 7 to server version: 4.1.9-max

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>
To carry out a task issue the sql statement (note the mysql client accepts non SQL command for mysql specific purposes such as 'show tables') followed by a ';'. Example:
mysql> select * from test;
+----------+
| test     |
+----------+
| ttesting |
+----------+
1 row in set (0.00 sec)
To exit from the mysql client type issue the 'exit' command. Those familiar with mysql will be aware that the client will normally require command line arguments to connect, for your convenience a .my.cnf file has been created which mysql uses to find which parameters to use when it connects to the database.

Using the psql command line client
If Postgres was chosen for the database and the account is ssh enabled, the psql client is in your PATH. To connect to the database use the following command:

psql -U username -h 127.0.0.1 username

Creating new databases
To create new (additional) databases within the mysql command line client use the 'create database dbname' syntax. An important restriction is the new database name must be prefixed with the root level database (the database automatically set up for you) name. For example, if your root level database is named rootlevel then creating a new database 'rootlevel_1' is acceptable, whereas 'nestedlevel' is unacceptable.

Starting Tomcat
The Tomcat home directory is located at /usr/tomcat and the startup and shutdown scripts are located within the bin sub-directory (startup.sh and shutdown.sh respectively). To start Tomcat cd into the /usr/tomcat diretory (cd /usr/tomcat) and type bin/startup.sh. You should see this output:

Using CATALINA_BASE: /usr/tomcat
Using CATALINA_HOME: /usr/tomcat
Using CATALINA_TMPDIR: /usr/tomcat/temp
Using JAVA_HOME: /usr/java/jdk

Stopping Tomcat
To stop Tomcat, from the same directory (/usr/tomcat) issue the following command: bin/shutdown.sh. You should see the same output which you saw when Tomcat was started. In some circumstances the JVM running Tomcat does not response to the shutdown command. To resolve this enter this line within the startup.sh script:
export CATALINA_PID=/tmp/tomcat.pid
If Tomcat refuses to shutdown using the shutdown.sh script issue this command:
kill `cat /tmp/tomcat.pid`
Viewing Logs
When running/debugging web applications it is often useful to view Tomcat's logs, particularly when unpredicted behaviour occurs. The log files are located with the /usr/tomcat/logs directory. The catalina.out file is where STDOUT and STDERR are sent. For example, if you used System.out.println(...) statements in your code this is where they will appear (unless you specify swallowOutput="true" for the Context element in the server.xml). A useful command to view the 'realtime' logs is to 'tail' this log with the -f switch while testing your application (tail -f /usr/tomcat/logs/catalina.out).
As log entries are inserted into the log file they will appear within the console. The other set of log files are specific to your application, for example the apache_log* logs will correspond to your web application(s). These contain logs from the web container as well as logs sent via your application with the log() methods contained within the ServletContext class.
Common Configuration Tasks
The primary source of Tomcat's configuration is within the server.xml file located within the /usr/tomcat/conf directory. Although expert users will understand it is now possible to split the configuration details over multiple files, the actual XML syntax of the contents is identical. The server.xml file can be viewed by a text editor such as vi or pico, it will typically look like this:
<Server port="8021" shutdown="SHUTDOWN" debug="0">
  <Service name="Tomcat-Apache">

    <Connector port="8082"
               enableLookups="false" redirectPort="8443" debug="0"
               protocol="AJP/1.3" />

    <!-- Replace "localhost" with what your Apache "ServerName" is set to -->
    <Engine className="org.apache.catalina.connector.warp.WarpEngine"
     name="Apache" debug="0" >
      <!-- Global logger unless overridden at lower levels -->
      <Logger className="org.apache.catalina.logger.FileLogger"
              prefix="apache_log." suffix=".txt"
              timestamp="true"/>
     <Host name="www.nameonthe.net" debug="99" unpackWARs="true" >
       <Context path="" docBase="/web" reloadable="true" >
       <!-- Tomcat 5.0.x releases -->
       <!--
       <Resource name="jdbc/dbconnection"
               auth="Container"
               type="javax.sql.DataSource"/>
          <ResourceParams name="jdbc/dbconnection">
            <parameter>
              <name>factory</name>
              <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
            </parameter>
            <parameter>
              <name>maxActive</name>
              <value>10</value>
            </parameter>
            <parameter>
              <name>maxIdle</name>
              <value>5</value>
            </parameter>
            <parameter>
              <name>maxWait</name>
              <value>10000</value>
            </parameter>
            <parameter>
             <name>username</name>
             <value>username</value>
            </parameter>
            <parameter>
             <name>password</name>
             <value>password</value>
            </parameter>
            <parameter>
               <name>driverClassName</name>
               <value>com.mysql.jdbc.Driver</value>
            </parameter>
            <parameter>
              <name>url</name>
              <value>jdbc:mysql://localhost:3306/dbname?autoReconnect=true</value>
            </parameter>
          </ResourceParams>
        --> 
       <!-- Tomcat 5.5.x releases -->
       <!--
       <Resource name="jdbc/jdbcname" auth="Container" type="javax.sql.DataSource" 
       driverClassName="com.mysql.jdbc.Driver" username="username" password="password" 
       url="jdbc:mysql://localhost/db?autoReconnect=true" maxActive="100" maxIdle="30" maxWait="10000" />
	-->
       </Context>
     </Host>
   </Engine>
 </Service>
</Server>
The ports attributes should never be altered, doing so will 'break' your Tomcat installation. The authoritative/canonical source of documentation detailing the elements contained within the server.xml file can be found
here

Deploying applications
When you view the root of your domain for the first time you will notice that a context has been configured to serve your application. If you are not going to use Servlets/Jsp the document root is /web, for example if you place a 'index.html' file inside this directory this will become your home page (this is configurable - see .htaccess reference). However, if your intent is to take advantage of Jsps and Servlets then you may wish to modify the default context which has been deployed. Note, 'context' and 'web application' are terms which are loosely interchangeable. The modes of deploying applications are given below.

(1) Default Context
There are three main methods of creating and/or deploying a web application, the choice you take will depend on your development environment and/or deployment process . By default a ROOT application will be defined when you start up Tomcat, the <Context> element in the configuration file above configures a ROOT context so all requests for http://www.yourdomain.com/index.jsp (and other Jsps) will be forwarded towards that context*. Similarly, requests for servlets which are mapped at the ROOT path will be dealt with using this context (http://www.yourdomain.com/servlet/myservlet)

*Note* Tomcat treats a web application called ROOT uniquely in giving it no path, i.e. a ROOT web application is visible at the 'root' path of the url - http://www.domain.com/

(2) Deploying using .war files
Web Application Resources (war) files are frequently used to deploy web applications. To deploy a .war file copy the .war file into the appBase directory (see the <host> element in the server.xml above). If Tomcat is configured to autoDeploy (again see the <host> element) then during start up or while Tomcat is running (assuming the liveDeploy attribute within the host element is set to "true") Tomcat will detect its presense and create a web application. The name of the war file is used to determine the path of the deployed web application, for example if the name is monday.war then a web application will be deployed using the path 'monday' which maps to urls under http://www.yourdomain.com/monday/. Tomcat can be configured to 'unjar' (see host element) the war file into the underlying uncompressed directory structure of the file, this can be useful during incremental development when you need to make changes to the web application while it is running.

ROOT war files
.war files with the name ROOT.war are given special treatment during deployment, when Tomcat detects and deploys the ROOT.war file instead of creating a web application mapped to (/warname).war it maps it to the ROOT url (http://yourdomain.com/). However, because the ROOT context is preconfigured within the server.xml above deploying a ROOT.war file will have no affect because a ROOT context already exists. To deploy ROOT.war files, stop Tomcat, remove the ROOT <context> and restart Tomcat.

(3)Deploying using directories
Tomcat is intelligent to understand that directories which resemble the structure of a web application that exist beneath the appBase directory are suitable candidates for deployment. If a directory contains a WEB-INF directory then Tomcat will attempt to deploy it. In reference to the special treatment of the symbolic ROOT creating a ROOT directory beneath the appBase will have the same affect as 1 or 2 (with a ROOT.war file).

(4)Deploying .xml files
The final method of deploying web applications is using .xml files within the appBase directory (now deprecated). Later versions of Tomcat also look with a special directory within its configuration directory for xml files to deploy: $TOMCAT_HOME/conf/Catalina/www.domain.com/ When Tomcat is running (assuming autoDeploy is set to true) or when started up it scans these directories for files with .xml extensions. The content(s) of this file(s) should have contain a 'context' element xml structure identical to what is expected within the server.xml. If the contents adhere to this specification (DTD) then Tomcat will deploy the application. The benefits of this approach over the above are you can specify Tomcat specific configuration options such as JNDI resources. However, there is no real difference between this option and editing the server.xml configuration file apart from being able to deploy xml files at runtime rather than start time.

Connection Pooling
A popular configuration option is to take advantage of connection pooling within Tomcat. In accordance to the Servlet 2.4/JSP 2.0 specification Tomcat provides a JNDI (Java Naming Directory Inteface) Context for each application, this allows an application to 'lookup' values and resources which have been configured within the server.xml and/or the web.xml file. This is how the connection pooling works, the steps taken to configure and use it are:
  • Define the resource inside the server.xml
  • Declare the resource inside the application's web.xml
  • Lookup the DataSource object
The definition of the DataSource is contained in the server.xml above commented out, to define it uncomment it and replace the url, driverClassName, username, password element values with values applicable to you.

The next step is to declare the resource within the web.xml file, ensure that when you enter the resource-ref element (and the element's within it) into the web.xml file it appears in the correct order to the other elements in compliance with the web.xml DTD.

<resource-ref>
   <description>DB Connection</description>
   <res-ref-name>jdbc/dbconnection</res-ref-name>
   <res-type>javax.sql.DataSource</res-type>
   <res-auth>Container</res-auth>
</resource-ref>
When the steps above have been completed restart Tomcat so the changes inside the server.xml will be applied. To use the connection pool a InitialContext must be found. The simple class below demonstrates how to obtain a javax.sql.DataSource and a java.sql.Connection object:
import java.sql.Connection;
import javax.sql.DataSource;
import javax.naming.InitialContext;
import javax.naming.Context;
import org.apache.log4j.Logger;

/**
 * Very simple ConnectionPool wrapper  
 *
 * @author James Williamson
 * @version 0.01
 */

public class ConnectionPool
{
   /** Our Logger object */
   private static Logger logger = 
     Logger.getLogger(ConnectionPool.class);

   public static Connection getConnection() {
     try {
     Context ctx = new InitialContext();
     if(ctx == null)
       logger.fatal("Cannot get initial Context");

      DataSource ds = 
       (DataSource)ctx.lookup("java:comp/env/jdbc/dbconnection");
      return ds.getConnection();

    } catch (Exception e) {
      logger.fatal("Cannot get connection",e);
      return null;
    }
  }
}
Tomcat Admin Application
The Tomcat admin application provides a web front end for configuring Tomcat, with the added bonus of it being able to commit your changes to the underlying server.xml file. As this is fundamentally a standard web application the process for installing it remain near synonymous with that of any other web application. However, there are two crucial aspects which differ and must be configured for it to function. The first is the admin application is 'privileged', that is it can access the ClassLoader used by the server side of Tomcat thus giving it the ability to modify the internal Tomcat configuration in realtime whereas a restart would normally be required. The second: it requires the use of Realms to ensure the administrator has authenticated themself before gaining entry.

A typical entry to configure the admin application is shown below, note that privileged attribute has been set to true and the evidence of a Realm used for authentication. The choice of Realm is configurable, in this instance the MemoryRealm is used (although database, LDAP and others are available). Because the path isn't specified as an attribute, Tomcat will by default look inside /usr/tomcat/conf/tomcat-users.xml for details of authentication information.

Section of server.xml used to configure Host and assoicated admin app

 <Host name="hostname">
  <Logger className="org.apache.catalina.logger.FileLogger"
       prefix="hostname." suffix=".log" directory="/home/username/logs"
       timestamp="true"/>
 <Realm className="org.apache.catalina.realm.MemoryRealm" />
 <-- The ROOT context -->
 <Context path="" appBase="/web" />
 <-- The admin context, this will be visible at http://www.hostname.com/admin -->
 <Context path="/admin" appBase="/web/admin" privileged="true" />
 </Host>>
Contents of the tomcat-users.xml file
<tomcat-users>
  <user name="tomcat" password="tomcat" roles="admin" />
</tomcat-users>
The roles attribute within the tomcat-users.xml file should map to the entry within the web.xml of the admin web app which declares the security role required to gain access to the application. By default the admin is set to 'admin' so the only change required is to modify the tomcat-users.xml file setting the desired username/password. Before restarting Tomcat ensure the admin directory exists in the path specified within the server.xml file. Once these changes are complete restart tomcat and redirect you browser to http://www.youdomain.com/admin/, you should be presented with an admin screen. Login using the username,password you suppliled within the tomcat-users.xml file. An important element of the admin app is it allows you to commit the changes you have made while using this app permanently, the 'commit changes' writes out the running config back to the server.xml.

Running Tomcat headless
If you are seeing stack traces with classes belonging to java.awt in them and are using image manipulation libraries that it is most likely you need to run Tomcat 'headless'. Adding this line into the top of the catalina.sh will instruct the JRE to start running within a 'headless' environment:

JAVA_OPTS-Djava.awt.headless=true

If errors occur the problem will often be related to the parameters given in the server.xml. Check the logs for stack traces indicating where the error occurred. If you require assistance email support@nameonthe.net.

Version: 1.1
Date: 15/05/2005

username
password
>> Login <<
Today's Tech Tip
Postgres Tip (No 150)
Print the psql history buffer to stdout using the \s meta command, i.e.
psql>\s
... psql command line history ...
Latest Java news
Oracle, BEA and the big virtual Java adventure
2008-06-26 11:09:00.0
MusicStation is fine tuned for Java handsets
2008-06-26 10:47:00.0
Sun To Set Up Education ...
2008-06-26 06:29:00.0
ImageMagick 6.4.2
2008-06-25 20:51:00.0
nameonthe.net news feed
System Status
(Fri Jul 04 14:47:32 BST 2008)
There are no known network or server problems

Valid XHTML 1.0!

Valid CSS!

Copyright © www.nameonthe.net 1999-2008, All Rights Reserved
All prices exclude VAT