ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

Adding Transactions to Servlets with JOTM
Pages: 1, 2

Configuring the Databases

For the database, we use MySQL 4.0.12 and its JDBC driver (see Resources). By default, MySQL tables are not transactional. To support transactions, the tables have to be created with the InnoDB type. In addition, to enable InnoDB type, you have to comment the line #skip-innodb in the MySQL configuration file, my.cnf.

The example is configured for the MySQL user javauser with a password of javadude. Make sure that this user is created and has the correct rights to create databases.

A script to create databases and tables is included in the example file in the scripts/ directory. It will create the account table and insert two clients:

  • john_doe with $100 in his account.
  • jane_doe with $600 in her account.

Example 2. account table creation

mysql> CREATE DATABASE banktest;
mysql> USE banktest;
mysql> CREATE TABLE account(
    -> money INT) TYPE=InnoDB;
mysql> INSERT INTO account VALUES("john_doe", 100);
mysql> INSERT INTO account VALUES("jane_doe", 600);
mysql> SELECT * FROM account;
| client   | money |
| john_doe |   100 |
| jane_doe |   600 |

The script will also create the atm table with $500 available cash.

Example 3. atm table creation

mysql> CREATE DATABASE atmtest;
mysql> USE atmtest;
mysql> CREATE TABLE atm(
    -> cash INT) TYPE=InnoDB;
mysql> INSERT INTO atm VALUES(null, 500);
mysql> SELECT * FROM atm;
| id | cash |
|  1 |  500 |

Finally, you have to copy the JDBC driver .jar file in $CATALINA_HOME/shared/lib.

Getting And Installing Tomcat

This article has been written for Tomcat 4.1.18 and above. Make sure you are not using an older version. There is nothing special to do when installing Tomcat, just download it and unzip it.

Getting and Installing JOTM

To use JOTM, you just have to download its latest binary release and unzip the file. Copy the .jar files (except log4j.jar, commons-cli.jar, and jotm_iiop_stubs.jar) from its lib/ directory to $CATALINA_HOME/shared/lib. That's all!

Configuring Tomcat

You now need to configure Tomcat to be able to get the UserTransaction and DataSource objects (which are used in foo.BankAccount and bar.ATM) from JNDI.

First, tell Tomcat which JNDI names you'll use to look up your data sources in your web application. This is done in web.xml file listed below. For the Bank Account data source, the JNDI name used is java:comp/env/jdbc/bankAccount, but you just have to give the name after the java:comp/env/. Tomcat will resolve the rest through the JNDI mechanism. The same thing has to be done for the ATM data source.

Example 4. web.xml

        <description>Bank Account DataSource</description>

        <description>ATM DataSource</description>

You now need to tell Tomcat how to retrieve the resources described in web.xml. This is done in the bank.xml file listed below. For both bank account and ATM resources, you must set parameters so that Tomcat can connect your web application to the data sources correctly. A more detailed description can be found in Tomcat JNDI DataSource How-to (see Resources).

One parameter is of specific interest: factory. The class set by this parameter will be used to create a data source when the web application looks it up through JNDI. Another important resource described in web.xml is UserTransaction. This resource is used by java:comp/UserTransaction to demarcate the transaction. The implementation of this resource is provided by JOTM.

Example 5. bank.xml

<Context path="/bank" docBase="bank.war" debug="0" reloadable="true" crossContext="true">

    <!-- Description of the DataSource "jdbc/bankAccount" -->
    <Resource name="jdbc/bankAccount" auth="Container" type="javax.sql.DataSource" />
    <ResourceParams name="jdbc/bankAccount">
            <!-- Factory of the DataSource -->
        <!-- other parameters include:
        o username - name of database user
        o password - password of the database user
        o driverClassName - JDBC Driver name

    <!-- Description of the DataSource "jdbc/ATM" -->
    <Resource name="jdbc/ATM" auth="Container" type="javax.sql.DataSource" />

    <!-- same type of parameters than for resource "jdbc/bankAccount" -->
    <ResourceParams name="jdbc/ATM">

    <!-- Description of the resource "UserTransaction -->
    <Resource name="UserTransaction" auth="Container" type="javax.transaction.UserTransaction" />
    <ResourceParams name="UserTransaction">

Deploying the Web Application

Once you've setup JOTM and Tomcat, deploying and using the web application is easy. First, download the file bank.tgz and unzip it. Copy bank.xml and bank.war into $CATALINA_HOME/webapps. Next, start TOMCAT:

> ./catalina.sh run
Using CATALINA_BASE:   /home/jmesnil/lib/tomcat
Using CATALINA_HOME:   /home/jmesnil/lib/tomcat
Using CATALINA_TMPDIR: /home/jmesnil/lib/tomcat/temp
Using JAVA_HOME:       /usr/local/java
May 6, 2003 5:56:00 PM org.apache.commons.modeler.Registry loadRegistry
INFO: Loading registry information
May 6, 2003 5:56:00 PM org.apache.commons.modeler.Registry getRegistry
INFO: Creating new Registry instance
May 6, 2003 5:56:00 PM org.apache.commons.modeler.Registry getServer
INFO: Creating MBeanServer
May 6, 2003 5:56:07 PM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on port 8080
Starting service Tomcat-Standalone
Apache Tomcat/4.1.24-LE-jdk14

You can notice in the logs that JOTM is not started yet. It will only be started when you will access a DataSource for the first time. At that time, you will have messages like:

May 6, 2003 5:56:20 PM org.objectweb.jotm.Jotm <init>
INFO: JOTM started with a local transaction factory that is not bound.
May 6, 2003 5:56:20 PM org.objectweb.jotm.Jotm <init>
INFO: CAROL initialization

Browse to the URL http://localhost:8080/bank/ to use the web application.

Using the Web Application

The home page of the web application contains two links:

1. To the Cash Delivery page, which you can use to simulate money withdrawal from an ATM.

Cash Delivery page screenshot
Figure 2. Cash Delivery page

2. To the management console, which you can use to check or update information related to the ATM or to the several bank accounts you've created.

Management Console screenshot
Figure 3. Management Console

Before any operations, there's $500 in the ATM. John Doe has $100 in his bank account and Jane Doe has $600 in hers.

If John Doe tries to withdraw $400, the transaction will fail, because there is not enough money in his bank account. The results will be:

Client ID: john_doe, value: $400

Cash can not be delivered to you
because: not enough money in your account (only $100).

If Jane Doe tries to withdraw $550, the transaction will fail, because there is not enough cash in ATM. The results will be:

Client ID: jane_doe, value: $550

Cash can not be delivered to you
because: not enough cash available from this ATM (only

If John Doe tries to withdraw $50, the transaction succeeds. The result will be:

Client ID: john_doe, value: $50

   Please take your cash ($50)
   Thank you!


This simple example demonstrates how servlets can provide robustness and simplicity by using transactions to ensure correct behavior in any case. Tomcat and JOTM combine well to take advantage of transactions in servlets in a lightweight way.

There is more to JOTM than what this simple example has shown. JOTM can help you to enhance your web application by providing:

  • Full distributed transaction support. If your layers (data, business, presentation) run in different JVMs, it is possible to have a global transaction that will span across the JVMs. A transaction context can be propagated on both RMI/JRMP and RMI/IIOP.
  • Integration with JDBC. The example used XAPool, an XA-compliant JDBC connection pool, to interact with the database. XAPool is similar to the Jakarta DBCP project, with the added feature of being XA-compliant, which is mandatory in order to use JTA transactions with JDBC.
  • Integration with JMS. JOTM can be combined with JORAM, a JMS provider developed by the ObjectWeb Consortium, to provide transactional JMS messages. You can have JMS message sendings and database updates occurring in the same transaction in your servlets.
  • Transactions for Web Services. JOTM provides an implementation of BTP (Business Transaction Protocol), JOTM-BTP, which can be used to add transactional behavior to your web services.

Examples and documentation for all of these features can be found in JOTM distributions and on its web site.


Jeff Mesnil is a Software Engineer at INRIA, where he works for the ObjectWeb Consortium on JOTM, an open source transaction manager in Java.

Return to ONJava.com.