Add a transaction to the servlet with JOTM

Source: Internet
Author: User
Tags auth getmessage rollback create database apache tomcat
In addition to providing a servlet, Java EE provides a number of other features. Servlet developers may rarely use these features, reluctantly and without the time to replace their own simple servlet with a large Java server that exceeds the requirements. However, depending on the modular nature of Java EE, it is possible to consolidate the WEB application by consolidating the team parts that are responsible for the particular Java EE functionality into the servlet container. One of them is business. For a complete description of the Java EE transaction, you can refer to the other three articles on Onjava, and now just know that the transaction is a resource's operational step (for example, a database), which is defined by four properties, which are condensed into ACID based on its initials:

  atomicity: The operation of the transaction, either all succeeded (at this point committing the transaction), or all unsuccessful (at this time the transaction is rolled back), which is referred to as the All-or-nothing property. A transaction should be treated as a single unit of work, and it is impossible to have both completed and unfinished operations within a transaction.

  Consistency: A completed transaction converts a resource from a valid state to another valid state. Specific examples of consistency are: referential integrity of the database and uniqueness of the primary key in the table.

  independence Before a transaction is committed, a change in the shared resources of a transaction is not visible outside of the transaction. Independence ensures that different transactions do not access the data that is being updated at the same time.

  Persistence : Changes committed by a transaction are persisted.

Jotm (Java Open Transaction Manager) is a fully functional and open resource independent transaction manager developed by the ObjectWeb Association. It provides transactional support for Java applications and is compatible with the JTA (Java transaction API). You can learn more about the Jotm home page. After the JOTM has been consolidated by TOMCAT (or other servlet containers), the developers of JSP and Servlet can gain the advantage of the transaction and easily create more robust web applications.

To highlight how a transaction enhances a Web application, a common example is the ATM that the Web browser interacts with the client.

  ATM Sample:

  Scenario

This example is simpler: a customer wants to withdraw from an ATM, enter his customer name, John_doe, and the number of withdrawals, $. If he had enough money on his bank account and had enough cash on the ATM, the app would give him a fair amount of cash and raise the same number from a bank account. Otherwise, the operation is interrupted, and no other changes are found except for the error message. We don't have to worry about security, just wondering if the user is properly authorized.

This is a very simple example, but if you do not use a transaction, it will be difficult to perform it in a different way. The client operation will involve two different resources: ATM and customer bank accounts. They automatically generate ACID problems in the application design. For example, if the operation succeeds on the ATM and fails on the bank account (perhaps due to communication failure), the customer will get the money, but his account will not be updated. For banks, this is a big loss. Worse still, if the bank account is updated, but because an error prevents the ATM from transferring money, the client is not getting cash, but the account is missing the sum.

In order to prevent these accidents, in your application you can contact two resources and tell them all the current operations performed by the customer, 2 to ask whether they can perform the operation, 3 if both agree, then request the operation. Even so, this method cannot be said to be robust enough, because if the money on the customer's account is removed by another operation at the second and third steps, the withdrawal may fail, for example, the customer account cannot have a deficit.

The thing that makes an application simpler and more robust is that it solves the ACID problem (especially atomicity) when all operations are performed on the two resources of the same transaction.

  Application Design

  Data layer: at the data layer, there are two different databases, each with a single table. To bring the example closer to reality, we use two different databases because it is possible to extract from an ATM a section that is not part of the customer account (see Configuration database below).

Banktest contains the Account table representing the customer account number.

Atmtest contains ATM tables that represent ATM.

  logical layer: at the logical level, there are three classes to access resources and perform actions:

Foo. BankAccount represents a given customer's bank account accounts and can perform database operations through JDBC.

Bar. ATM represents ATM and performs JDBC operations on ATM tables.

Bar. Cashdelivery uses the previous two classes to perform a customer operation.

All logic is implemented in the Cashdelivery.java Delivercash method.

The Javax.transaction.UserTransaction interface is used to divide the operations between the Utx.begin () and Utx.commit () (or Utx.rollback ()) within the same transaction. This ensures that the application will not suffer as described earlier.

Transactions make the application simpler and consist of the following simple steps:

1. Start the business.

2. Contact the customer's bank account and withdraw money from the account.

3. Tell ATM to send money.

4. Completion of transaction: If all events are completed, commit the transaction. Otherwise, the transaction is rolled back.

5. Report customer transaction results. If the transaction succeeds, the cash will be raised and the amount will be raised from the account. Otherwise, nothing will change.

Example 1. Cashdelivery.java

 public boolean deliver (String client, int value) {InitialContext CTX = new Initialcon
Text ();
    UserTransaction UTX = (usertransaction) ctx.lookup ("Java:comp/usertransaction");
... boolean success = false;

try {//Start transaction utx.begin ();
Contact Customer Bank Account ...

BankAccount account = new BankAccount (client); // ...

Withdraw Account.withdraw (value) from the account;
Contact ATM ...

ATM ATM = new ATM (); // ...

Transfer cash to Customer Atm.delivercash (value);

All normal success = true;

catch (Exception e) {//failed, had to//report to Customer explanation + + e.getmessage ();
                Finally {try {if (success) {* * All normal commit transactions until now, the money is actually raised from the account and the cash is delivered to the customer.

* * Utx.commit ();
} else {/* fails, ROLLBACK TRANSACTION.
                * All operations handled within a transaction do not occur.
            * * Utx.rollback (); The catch (Exception e) {/* fails during the completion of the transaction, * still guarantees that the operation within the transaction does not occur.

/////Report to Customer explanation + = "N" + e.getmessage ();

Finally, the transaction does not succeed success = false;
        finally {return success; }
    }
}

  presentation layer: at the presentation layer, the program consists of two JSP files:

Atm.jsp, the application, which is sent to bar. Cashdelivery the number of customer logins and withdrawals and displays the results of customer operations.

Admin.jsp, for displaying and updating information about two resources. (It's not part of the application design, but it's added to simplify resource updates, such as handling the amount of money in a customer account.) )

Figure 1 Application Design

  Configuration Database

With regard to databases, it is recommended that you use the MySQL 4.0.12 and the appropriate JDBC driver (see Resources). By default, the MySQL table will not be affected. To support transactions, tables are set to the InnoDB type when they are created. In addition, to enable the InnoDB type, you can comment out the #skip-innodb line in the MySQL configuration file.

A MySQL example has been configured with a username of Javauser and a password of javadude. Make sure that the user has been created and has permission to create the database.

Scripts to create databases and tables are contained in example file under the scripts/directory. It will create an account table and insert two customers: John_doe The amount of his accounts is $. Jane_doe The amount of his account is $600.

Example 2 creating an Account table

mysql> CREATE DATABASE banktest;
mysql> use banktest;
Mysql> CREATE TABLE Account (
-> client VARCHAR is not NULL PRIMARY KEY,-> money
INT) Type=innodb;
Mysql> INSERT into account ValueS ("John_doe",);
Mysql> INSERT into account ValueS ("Jane_doe",);
Mysql> SELECT * from account;
+----------+-------+
| client   | money |
+----------+-------+
| john_doe |   |
| Jane_doe |   |
+----------+-------+

The script also creates an ATM table with cash available for $ $.

Example 3 Creating an ATM table

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,);
Mysql> SELECT * from ATM;
+----+------+
| id | cash |
+----+------+
|  1 |  |
+----+------+

Finally, copy the JDBC driver within the $CATALINA _home/shared/lib. jar file.

  Get and install Tomcat: This chapter mainly introduces the version of Tomcat 4.1.18 and above. First make sure that no previous versions are used and that there is nothing special about installing TOMCAT, just download and unzip it.

  Get and install Jotm: If you want to use JOTM, you only need to download the most recent two-dollar version and unzip it. Then copy the. jar files (except Log4j.jar, Ommons-cli.jar, and Jotm_iiop_stubs.jar) from the lib/directory to $CATALINA _home/shared/lib. So it's done.

  Configure Tomcat: you need to configure Tomcat to enable it to get usertransaction and DataSource objects from JNDI (they are used in Foo. BankAccount and Bar. ATM).

First, tell TOMCAT the JNDI name you are using to query the data source in the WEB application. These steps are completed by Web.xml with the following code. For a bank account data source, the JNDI name used is Java:comp/env/jdbc/bankaccount and can only be given a name after java:comp/env/. TOMCAT solves the remaining problems through the JNDI mechanism. The same is true for ATM data sources.

Example 4. 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 must tell TOMCAT how to return the resources within Web.xml, and this process is done by the Bank.xml file. For bank accounts and ATM resources, you must set parameters so that TOMCAT can connect the WEB application to the data source correctly. For more detailed information, refer to the TOMCAT JNDI data source basics. (See Resources)

One of the parameters requires special attention: the Factory. Class sets this parameter to create a data source when the WEB application passes through a JNDI query. Another important resource (described in Web.xml) is usertransaction. Java:comp/usertransaction uses this resource to differentiate between transactions, which are performed 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> & lt;! --Description of the DataSource "JDBC/ATM"--> <resource name= "Jdbc/atm" auth= "Container" type= Rce "/> <!--same type of parameters than for resource" Jdbc/banKaccount "--> <resourceparams name= jdbc/atm" > ... </ResourceParams> <!--Description of the RE SOURCE "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>

  To expand a Web application: Once you've set up Jotm and Tomcat, it's easy to expand and use a Web application. First, download the bank.tgz and unzip it, then copy Bank.xml and Bank.war to the $CATALINA _home/webapps, and then 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:i Nitializing Coyote http/1.1 on port 8080
starting service Tomcat-standalone
Apache tomcat/4.1.24-le-jdk14

You will find in the log that JOTM has not yet started. It starts when you first visit DataSource, at which point you will find the following information:

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

Type urlhttp://localhost:8080/bank/to use the WEB application.

  using WEB applications

The homepage of the WEB application contains two links:

1. It's the Cash Delivery page where you can draw money like you would at an ATM.

Figure 2 Cash Delivery page

2. Management console, where you can detect or update ATM or bank accounts that you create yourself.

Figure 3 Management Console

Prior to operation, ATM has $500,john Doe bank account with $, Jane Doe bank account has $600.

If John Doe wants to take the $, the deal will fail because there is not enough balance on his account. The result will be:

Client Id:john_doe, Value: $

Cash can is delivered to you

Because:not enough in your account (only $).

If Jane Doe wants to take $550, the deal will fail because there is not enough cash on the ATM. The result will be:

Client Id:jane_doe, Value: $550

Cash can is delivered to you

Because:not enough cash available from this ATM.

If John Doe takes the $, the deal will be successful. The result will be:

Client Id:john_doe, Value: $

Please take your cash ($)

Thank you!

  Summary

This simple example demonstrates how the servlet provides robustness and simplification by using transactions, and ensures that it is correct in all cases. The perfect combination of Tomcat and JOTM makes it easy for the servlet to gain the advantage of the transaction.

In addition to the simple example above, JOTM has many more advantages. JOTM provides the following performance to help enhance WEB applications.

1. Full distributed transaction support. If the data tier, business layer, and presentation layer are running on different JVMs, there is a possibility of a full transaction span of these JVMs, and the content of the transaction is propagated on RMI/JRMP and RMI/IIOP.

2. Consolidate JDBC. The Xapool example used is a xa-compatible JDBC connection pool that can interoperate with the database. Xapool is similar to Jakarta DBCP, but adds xa--compatible features that must be adhered to if you want to use JTA transactions with JDBC.

3. Integrate JMS. Jotm can combine Joram to provide JMS messages for transactions by the JMS provider developed by the ObjectWeb Association. You can get a JMS message sender and an updated database that appears in the same transaction in the servlet.

4.WEB service transaction. JOTM provides BTP (Business Transaction Protocol), JOTM-BTP interfaces, which are used to increase transactional behavior in WEB services.

Samples and documents for all of these features can be found on Jotm's files and Web sites.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.