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_doewith $100in his account.jane_doewith $600in her account.
Example 2. account table creation
mysql> CREATE DATABASE banktest;
mysql> USE banktest;
mysql> CREATE TABLE account(
-> client VARCHAR(25) NOT NULL PRIMARY KEY,
-> 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(
-> id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> 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
<web-app>
<resource-env-ref>
<description>Bank Account DataSource</description>
<resource-env-ref-name>jdbc/bankAccount</resource-env-ref-name>
<resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>
<resource-env-ref>
<description>ATM DataSource</description>
<resource-env-ref-name>jdbc/ATM</resource-env-ref-name>
<resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>
</web-app>
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">
<parameter>
<!-- Factory of the DataSource -->
<name>factory</name>
<value>org.objectweb.jndi.DataSourceFactory</value>
</parameter>
<parameter>
<name>url</name>
<value>jdbc:mysql://localhost/banktest</value>
</parameter>
<!-- other parameters include:
o username - name of database user
o password - password of the database user
o driverClassName - JDBC Driver name
-->
...
</ResourceParams>
<!-- 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">
...
</ResourceParams>
<!-- Description of the resource "UserTransaction -->
<Resource name="UserTransaction" auth="Container" type="javax.transaction.UserTransaction" />
<ResourceParams name="UserTransaction">
<parameter>
<name>factory</name>
<value>org.objectweb.jotm.UserTransactionFactory</value>
</parameter>
<parameter>
<name>jotm.timeout</name>
<value>60</value>
</parameter>
</ResourceParams>
</Context>
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:
> cd $CATALINA_HOME/bin
> ./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.

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.

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
$500).
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!
Summary
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.
Resources
The example code can be downloaded from this .tgz file. It includes the web application (bank.war) and its descriptor (bank.xml). Sources are also included, and a Ant build file is provided to compile and package the application. You will need jta-spec1_0_1.jar in your classpath to compile the example (the .jar is in the lib/ directory of the JOTM installation).
ONJava.com has published a series of articles about J2EE Transactions:
"J2EE Transaction Frameworks: Building the Framework"
"J2EE Transaction Frameworks: Distributed Transaction Primer"
"J2EE Transaction Frameworks, Part 3"The ObjectWeb Consortium is an open-source-software community created at the end of 1999 whose goal is the development of open source, distributed middleware in the form of flexible and adaptable components.
The example uses MySQL 4.0.12 and its JDBC driver.
Tomcat 4.1.24 is the reference implementation for the Servlets 2.3 and JSP 1.2 specifications. Tomcat's documentation contains a how-to about DataSource JNDI configuration.
Jetty is another popular open source servlet container. As of version 4.2.10, Jetty integrates JOTM to provide out-of-the-box transaction support to servlets (see the JettyPlus page).
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.
-
Dangerous and misleading
2004-04-05 02:53:16 guypardon [View]
-
Two phase commit and MySQL ?
2003-08-08 03:04:46 anonymous2 [View]
-
Transaction is flawed
2003-07-31 15:32:01 anonymous2 [View]
-
transactions and the web
2003-07-31 05:27:31 anonymous2 [View]