img tele

(转贴)How to use JDBC and transactions in Tomcat with JOTM

发表于2004/9/14 11:16:00  1116人阅读

How to use JDBC and transactions in Tomcat with JOTM

Target audience

This howto is intended to Servlet/JSP developpers using Tomcat who want to take advantage of distributed transactions when using JDBC code in their servlets

This howto was written based on the JNDI Datasource HOW-TO provided by Tomcat.

It has been written for:

  • Tomcat 4.1.18
  • JOTM 1.4

It has been successfully reported to work on

  • MySQL
    • version 4.0.12, using InnoDB
    • with mysql-connector-java version 2.0.14
  • PostgreSQL
    • version 7.3.1
    • with pg73jdbc2.jar

1. Introduction

JOTM (Java Open Transaction Manager) is a transaction manager written in Java and implementating JTA (Java Transaction API). It is an Open Source project released under a BSD-style license.

Tomcat is the servlet container that is used in the official Reference Implementation for the Java Servlet and JavaServer Pages (JSP) technologies. Tomcat is released under the Apache Software License

MySQL configuration

Ensure that you follow these instructions as variations can cause problems.

Create a new test user, a new database and a single test table. Your MySQL user must have a password assigned. The driver will fail if you try to connect with an empty password.

mysql> GRANT ALL PRIVILEGES ON *.* TO mojo@localhost
mysql> create database javatest;
mysql> use javatest;
mysql> create table testdata (
    ->   id int not null auto_increment primary key,
    ->   foo int)type=InnoDB;

Note: the above user should be removed once testing is complete!

Next insert some test data into the testdata table.

mysql> insert into testdata values(null, 1);
Query OK, 1 row affected (0.00 sec)
mysql> select * from testdata;
| ID | FOO |
|  1 |   1 |
1 row in set (0.00 sec)

PostgreSQL configuration is similar.

Installing Required JARs

In order for a web application to use JOTM, the webapp and Tomcat need to have access to the JOTM jars, as well as the jars it requires

Here is a list of the required jars. They are all included with JOTM 1.4 binary distribution, available at http://www.objectweb.org/jotm

  • in the lib/ directory
    • jotm.jar
    • jotm_jrmp_stubs.jar
    • jonas_timer.jar
    • carol.jar
    • jta-spec1_0_1.jar
    • jts1_0.jar
    • objectweb-datasource.jar
    • xapool.jar

All these jar files need to be placed on $TOMCAT_HOME/common/lib/ so that both Tomcat and your web application will see them.

You also need to copy the jar of your JDBC driver to $TOMCAT_HOME/common/lib/.

Configuring JOTM

You'll need to create a file named carol.properties with the following properties:

# lmi stands for Local Method Invocation (it's a "fake" RMI)
# do not use CAROL JNDI wrapper
# do not start a name server

this file needs to be placed on $TOMCAT_HOME/common/classes/ so that Tomcat and JOTM will see it.

Configuring Tomcat

server.xml configuration

Now that you've installed JOTM in Tomcat, you need to configure Tomcat so that it can access JDBC and transaction resources. This is done in the dbtest.xml file which will be used by Tomcat to initialize the resources used by your web application.

<Context path="/dbtest" docBase="dbtest.war" debug="0"
  reloadable="true" crossContext="true">
  <!-- Resource configuration for JDBC datasource
       use XAPool
  <Resource name="jdbc/myDB" auth="Container"
  <ResourceParams name="jdbc/myDB">
    <!-- configured by default for PostgreSQL, just change the values
         to set it for your database
  <!-- Resource configuration for UserTransaction
  use JOTM
  <Resource name="UserTransaction" auth="Container"
  <ResourceParams name="UserTransaction">

web.xml configuration

Now you have to configure the web.xml file of your web application

<?xml version="1.0" encoding="ISO-8859-1"?>
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
      DB Connection

Test Code

Now create a simple test.jsp for use later.

    <title>DB Test</title>
    String completion = request.getParameter("completion");
    foo.DBTest test = new foo.DBTest();
    <h2>Transaction completion</h2>
    Transaction completion is :<strong><%= completion %></strong>
    Int stored in JDBC : <strong><%= test.getFoo() %></strong><br />
    <hr />
    <form action="test.jsp" method="get">
      <input type="radio" name="completion" value="commit" checked="true"> Commit<BR>
      <input type="radio" name="completion" value="rollback">Rollback<BR>
      <button type="submit">Completion</button>

And create a Java class to actually use your new Datasource and transactions. Note: this code isn't anywhere near production ready - it's only supposed to be used as a simple test :-)

package foo;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import javax.transaction.UserTransaction;
public class DBTest{
    int foo = -1;
    // value stored in DB
    public void init(String completion) {
            Context ctx = new InitialContext();
            // JDBC stuff
            DataSource ds =
            UserTransaction ut = (UserTransaction)ctx.lookup("java:comp/UserTransaction");
            java.sql.Connection conn = ds.getConnection();
            System.out.println("<<< beginning the transaction >>>");
             // JDBC statements
             Statement stmt = conn.createStatement();
             ResultSet rst =
                 stmt.executeQuery("select id, foo from testdata");
             if(rst.next()) {
             System.out.println("foo = "+ foo +" (before completion)");
             PreparedStatement pstmt = conn.prepareStatement("update testdata set foo=? where id=1");
              if (completion != null && completion.equals("commit")) {
                  System.out.println("<<< committing the transaction >>>");
              } else {
                  System.out.println("<<< rolling back the transaction >>>");
             // we set foo to the value stored in the DB
             rst =
                 stmt.executeQuery("select id, foo from testdata");
             if(rst.next()) {
             System.out.println("foo = "+ foo +" (after completion)");
             System.out.println("<<< done >>>");
        }catch(Exception e) {
            System.out.print("DBTest >> ");
    public String getFoo() { return ""+foo; }

Finally deploy your web app into $CATALINA_HOME/webapps as a warfile called dbtest.war.

Once deployed, point a browser at http://localhost:8080/dbtest/test.jsp to view the fruits of your hard work.

0 0



取 消