Use jotm to add a transaction to the Servlet

Source: Internet
Author: User
In addition to servlet, J2EE also provides a large number of other functions. Servlet developers may rarely use these features, and are reluctant to use a large J2EE server that exceeds the required time to replace their own simple servlet. However, based on the modular features of J2EE, it is possible to integrate small components responsible for specific J2EE functions into servlet containers to Enhance web applications. Program . One of them is a transaction. For a complete description of J2EE transactions, refer to the other three articles on onjava. Article Now, you only need to know that the transaction is the operation step of the resource (for example, the database), which is defined by four attributes, which are condensed into acid according to the first letter:

Atomicity:The transaction operation, or all succeeded (the transaction is committed at this time), or all failed (the transaction is rolled back at this time), is called the all-or-nothing attribute. A transaction should be regarded as a single unit of work. It is absolutely impossible for a transaction to have completed and unfinished operations at the same time.

Consistency:The completed transaction changes the resource from one valid state to another valid state. Examples of consistency include the integrity of the database and the uniqueness of the primary key in the table.

IndependenceBefore a transaction is committed, changes to the shared resources used by the transaction are invisible outside the transaction. Independence ensures that different transactions do not simultaneously access the data being updated.

Durability: Changes committed by transactions will exist permanently.

Jotm (Java open Transaction Manager) is an independent transaction manager with complete functions and open resources developed by the objectweb Association. It provides transaction support for Java applications and is compatible with JTA (Java transaction API. You can learn more on jotm home page. After Tomcat (or other servlet containers) integrates jotm, JSP and Servlet developers can easily create more robust web applications with transaction advantages.

To highlight how transactions enhance web applications, a common example is the ATM used by Web browsers to interact with clients.

ATM example:

Scenario

This example is relatively simple: a customer wants to withdraw money from an ATM and enters his customer name, john_doe; number of withdrawals, $50. If his bank account has enough money and enough cash on the ATM, the application can give him a considerable amount of cash and propose the same amount from the bank account. Otherwise, the operation is interrupted and will not change except for the error message. We don't need to worry about security issues. We just want to guess whether users are authorized correctly.

This is a very simple example, but if you do not use transactions, it will be difficult to execute them in other ways. Client operations involve two different resources: ATM and customer bank account. They automatically generate acid Problems in Application Design. For example, if the operation succeeds on the ATM but fails on the bank account (maybe because of communication failure), the customer will get the money, but his account will not be updated. This is a big loss for banks. Even worse, if the bank account is updated, but the client cannot get the cash due to an error that prevents money from being transferred by the ATM, the money is removed from the account.

In order to prevent the above incidents, in your application, you can 1) contact two resources and notify the two customers of all the current operations, 2) ask whether the two can perform the operations, 3) if both of them agree, request the operation. Even so, this method cannot be said to be robust enough, because if the money in the Customer Account is extracted by another operation in step 2 and step 3, the withdrawal may fail, for example, the customer account cannot have a deficit.

A transaction makes the application simpler and more robust: When you execute all the operations on the two resources of the same transaction, it will solve the acid problem (especially atomicity ).

Application Design

Data Layer:At the data layer, there are two different databases and each has a table. To make the example closer to reality, we use two different databases, because it is possible to extract money from the ATM that does not belong to the Customer Account (see the following section for database configuration ).

Banktest contains the account table representing the customer account.

The ATM test contains the ATM table representing the ATM.

Logic layer:At the logic layer, there are three classes to access resources and perform operations:

Foo. bankaccount indicates the account of the customer's bank account, and can perform database operations on the account through JDBC.

Bar. ATM stands for ATM and performs JDBC operations on the ATM table.

Bar. cashdelivery uses the first two classes to perform a customer operation.

All logics are implemented in the delivercash method of cashdelivery. java.

The javax. transaction. usertransaction interface is used to divide the operations between utx. Begin () and utx. Commit () (or utx. rollback () performed in the same transaction. This ensures that the application will not be affected as described above.

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

1. Start the transaction.

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

3. Tell the ATM to transfer money.

4. Complete the transaction: If all events are completed, submit the transaction. Otherwise, roll back the transaction.

5. Report customer transaction results. If the transaction succeeds, the cash will be raised, and the amount of money will also be raised from the account. Otherwise, everything will not change.

Example 1. cashdelivery. Java

      
      Public Boolean deliver (string client, int value) {initialcontext CTX = new initialcontext (); usertransaction utx = (usertransaction) CTX. lookup ("Java: COMP/usertransaction ");... boolean success = false; try {// start transaction utx. begin (); // contact the customer's bank account... bankaccount account = new bankaccount (client );//... withdraw an account from an account. withdraw (value); // contact ATM... ATM = new ATM ();//... transfer cash to the customer's ATM. delivercas H (value); // everything is normal success = true;} catch (exception e) {// The fault occurs and you have to // report it to the customer for explanation + = E. getmessage () ;}finally {try {If (SUCCESS) {/* all normal transactions are committed until now, money is actually raised from the account, and cash is transferred to the customer. */Utx. Commit ();} If else {/* fails, roll back the transaction. * All operations processed within the transaction will not occur. */Utx. rollback () ;}} catch (exception e) {/* If a fault occurs when the transaction is completed, * the operation in * the transaction is still not guaranteed. /* /// Report to the customer for explanation + = "/N" + E. getmessage (); // Finally, the transaction will not succeed. Success = false;} finally {return success ;}}

Presentation Layer:In the presentation layer, a program is composed of two JSP files:

ATM. jsp, an application that sends the number of logins and withdrawals to bar. cashdelivery customers and displays the results of customer operations.

Admin. jsp, used to display and update information of two resources. (It is not part of the application design, but it is added to simplify resource updates, such as processing the amount of money in the Customer Account .)

 

Figure 1 Application Design

Configure Database

For the database, we recommend that you use MySQL 4.0.12 and the corresponding JDBC Driver (see resources ). By default, MySQL tables are not affected. To support transactions, the table is set to the InnoDB type during creation. In addition, to enable the InnoDB type, you can comment out the # Skip-InnoDB line in the MySQL configuration file.

You have configured a MySQL example with the username javauser and password javadude. Make sure that the user has been created and has the permission to create a database.

The script for creating databases and tables is included in the example file in the scripts/directory. It will create an account table and insert two customers: john_doe whose account amount is $100. Jane_doe his account amount is $600.

Example 2 create an account table

      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 also creates an ATM table with $500 cash available.

Example 3 create an ATM table

      Mysql> Create Database ATM test; mysql> use ATM test; 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, copy the JDBC driver. jar file in $ catalina_home/shared/lib.

Get and install Tomcat:This chapter describes Tomcat 4.1.18 and later versions. First, make sure that the old version is not used and tomcat installation is not special. You only need to download and decompress the package.

Get and install jotm:To use jotm, you only need to download the latest binary version and decompress it. Copy the. jar file (except log4j. jar, ommons-cli.jar, and jotm_iiop_stubs.jar) from the LIB/directory to $ catalina_home/shared/lib. This completes.

Configure Tomcat:You need to configure tomcat to obtain 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 a web application. These steps are completed by web. xml.CodeAs follows. For the bank account data source, the JNDI name is Java: COMP/ENV/jdbc/bankaccount, and the name can only be given after Java: COMP/ENV. Tomcat uses the JNDI mechanism to solve other problems. The same applies to ATM data sources.

Example 4: Web. xml

       
       
       
        
        
          bank account datasource 
         
        
          JDBC/ bankaccount 
         
        
          javax. SQL. datasource 
         
        
       
         ATM datasource 
        
       
         JDBC/ATM  
        
          javax. SQL. datasource 
          
       
       

You must tell Tomcat how to return resources in Web. xml. This process is completed by the bank. xml file. For bank accounts and ATM resources, you must set parameters so that Tomcat can correctly connect the web application to the data source. For more information, see the basic knowledge of the Tomcat JNDI data source. (See resources)

One of these parameters requires special attention: this parameter is set in the factory. Class to create a data source when a web application queries through JNDI. Another important resource (described in Web. XML) is usertransaction. Java: COMP/usertransaction uses this resource to differentiate transactions, which are executed 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. performancefactory </value> </parameter> <Name> URL </Name> <value> JDBC: mysql: // localhost/banktest </value> </parameter> <! -- Other parameters include: O username-name of database usero password-password of the database usero 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> <Name> jotm. timeout </Name> <value> 60 </value> </parameter> </resourceparams> </context>

Expand the web application:Once you have set jotm and tomcat, it is easy to expand and use web applications. Download and decompress bank. tgz, copy bank. xml and bank. War to $ catalina_home/webapps, and start Tomcat:

       
       Cd $ catalina_home/bin>. /Catalina. sh runusing catalina_base:/home/jmesnil/lib/tomcatusing catalina_home:/home/jmesnil/lib/tomcatusing catalina_tmpdir:/home/jmesnil/lib/tomcat/tempusing java_home: /usr/local/javamay 6, 2003 5:56:00 Org. apache. commons. modeler. registry loadregistryinfo: loading registry informationmay 6, 2003 5:56:00 Org. apache. commons. modeler. registry getregistryinfo: creating new registry instancemay 6, 2003 5:56:00 Org. apache. commons. modeler. registry getserverinfo: Creating mbeanservermay 6, 2003 5:56:07 Org. apache. coyote. http11.http11protocol initinfo: initializing coyote HTTP/1.1 on port 8080 starting service tomcat-standaloneapache tomcat/4.1.24-LE-jdk14 

You will find in the log that jotm has not been started. It is started only when you access datasource for the first time. At that time, you will find the following information:

      May 6, 2003 5:56:20 Org. objectweb. jotm. jotm <init> info: jotm started with a local transaction factory that is not bound. may 6, 2003 5:56:20 Org. objectweb. jotm. jotm <init> info: Carol Initialization

Type urlhttp: // localhost: 8080/Bank/to use the Web application.

Use Web Applications

The Web application Homepage contains two links:

1. It is the cash delivery page, where you can withdraw money like at an ATM.

 

Figure 2 cash delivery page

2. It is the Management Console where you can detect or update an ATM or a self-created bank account.

 

Figure 3 Management Console

Prior to the operation, ATM had $500, John Doe bank account had $100, and Jane Doe bank account had $600.

If John Doe wants to get $400, the transaction will fail because there is not enough balance in his account. The result 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 wants to get $550, the transaction will also fail because there is not enough cash on the ATM. The result 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 gets $50, the transaction will succeed. The result will be:

Client ID: john_doe, value: $50

Please take your cash ($50)

Thank you!

Summary

This simple example demonstrates how servlet provides robustness and simplicity by using transactions and ensures that they are correct under any circumstances. The perfect combination of Tomcat and jotm makes it easy to obtain the transaction advantage in servlet.

In addition to the simple examples above, jotm has more advantages. Jotm provides the following performance to help enhance web applications.

1. fully Distributed Transaction support. if the data layer, business layer, and presentation layer run on different JVMs, there may be a full transaction span for these JVMs, and the transaction content is transmitted on RMI/jrmp and RMI/IIOP.

2. Integrate JDBC. The xapool example is an Xa-compatible JDBC connection pool that can operate with databases. Xapool is similar to Jakarta DBCP, but adds XA-compatible features. To use JTA transactions in combination with JDBC, this feature must be followed.

3. Integrate JMS. Jotm can work with Joram to provide transaction JMS messages by the "JMS provider" developed by the objectweb Association. You can get the JMS message sender and updated database that appears in the same transaction in the servlet.

4. Web service transactions. Jotm provides BTP (Business Transaction Protocol), JOTM-BTP interfaces that are used to add transaction behavior in Web Services.

Examples and documents of all these features can be found on the jotm file and website.

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.