(Reposted) How to use jdbc and transactions in Tomcat with Jotm

xiaoxiao2021-03-06  56

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.18JOTM 1.4

IT Has Been SuccessFully Reported to Work ON

Mysql

Version 4.0.12, using Innodbwith MySQL-Connector-Java Version 2.0.14PostgreSQL

Version 7.3.1with pg73jdbc2.jar

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 an an an an an an escher password.

MySQL> Grant All privileges on *. * to mojo @ localhost

-> Identified by 'Jojo' with grant option;

Mysql> Create Database Javates

Mysql> Use javatest;

Mysql> Create Table TestData

-> ID INT NOT NULL AUTO_INCREMENT Primary Key,

-> foo int) TYPE = INNODB;

MySQL>

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)

MySQL>

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 area all include the jotm 1.4 binary distribution, available at http://www.objectweb.org/jotm

In the lib / Directory

Jotm.jarjotm_jrmp_stubs.jarjonas_timer.jarcarol.jarjta-Spec1_0_1.jarjts1_0.jarobjectWeb-DataSource.jarxapool.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 folowing property:

# l l s s l v v (it's a "fake" RMI)

Carol.Protocols = LMI

# do not use carol jndi wrapper

Carol.start.jndi = false

# do not start a name server

Carol.start.ns = false

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.

Reloadable = "true" crossText = "true">

->

TYPE = "javax.sql.datasource" />

factory

Org.ObjectWeb.jndi.DataSourceFactory

To set it for your database

->

username Mojo

Password jojo

driverclassname

Org.postgreSQL.Driver

URL

jdbc: postgreSQL: // localhost / javatest

driverclassname

org.gjt.mm.mysql.driver

URL

jdbc: mysql: // localhost / javatest

->

Use jotm

->

TYPE = "javax.transaction.usertransaction" />

factory

Org.ObjectWeb.Jotm.UserTransActionFactory

jotm.timeout

60

Web.xml configuration

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

"- // Sun Microsystems, Inc.//dtd Web Application 2.3 // En"

"http://java.sun.com/dtd/web-app_2_3.dtd">

DB Connection

JDBC / MYDB

Javax.sql.datasource

Test Code

Now Create a Simple Test.jsp for Use.

DB Test </ Title></p> <p></ hEAD></p> <p><body></p> <p><%</p> <p>String completion = request.getParameter ("completion");</p> <p>Foo.dbtest test = new foo.dbtest ();</p> <p>TEST.INIT (Completion);</p> <p>%></p> <p><H2> Transaction Completion </ h2></p> <p>Transaction completion is: <strong> <% = completion%> </ strong></p> <p><H2> Results </ h2></p> <p>Int Stored in JDBC: <strong> <% = Test.getfoo ()%> </ strong> <br /></p> <p><hr /></p> <p><form action = "Test.jsp" Method = "get"></p> <p><Input Type = "Radio" name = "completion" value = "commit" Checked = "true"> commit <br></p> <p><Input Type = "Radio" name = "completion" value = "rollback"> rollback <br></p> <p><Button Type = "Submit"> Completion </ Button></p> <p></ form></p> <p></ body></p> <p></ html></p> <p>And create a java class to action and transactions. Note: this code isn't Anywhere Near Production Ready - It's Only Suppodosed to Be Used as a Simple Test :-) package foo;</p> <p>Import java.sql.preparedStatement;</p> <p>Import java.sql.resultset;</p> <p>Import java.sql.statement;</p> <p>Import javax.naming.context;</p> <p>Import javax.naming.initialcontext;</p> <p>Import javax.sql.datasource;</p> <p>Import javax.transaction.usertransaction;</p> <p>Public class dbtest {</p> <p>INT foo = -1;</p> <p>// Value Stored in DB</p> <p>Public void init (string company) {</p> <p>Try {</p> <p>Context ctx = new initialContext ();</p> <p>// jdbc stuff</p> <p>DataSource DS =</p> <p>(Datasource) CTX.lookup ("Java: Comp / Env / JDBC / MYDB");</p> <p>UserTransaction UT = (Usertransaction) CTX.lookup ("Java: Comp / UsertransAction);</p> <p>Java.sql.Connection conn = ds.getConnection ();</p> <p>System.out.println ("<<< Beginning The Transaction >>);</p> <p>Ut.begin ();</p> <p>// jdbc statements</p> <p>Statement Stmt = conn.createstatement ();</p> <p>ResultSet RST =</p> <p>Stmt.executeQuery ("SELECT ID, FOO from TestData);</p> <p>IF (Rst.Next ()) {</p> <p>Foo = Rst.Getint (2);</p> <p>}</p> <p>System.out.println ("Foo = foo ");</p> <p>PreparedStatement PSTMT = conn.preparestatement ("Update TestData set foo =? Where id = 1");</p> <p>PSTMT.Setint (1, foo);</p> <p>PSTMT.ExecuteUpdate ();</p> <p>IF (Completion! = Null && Completion.equals ("Commit")) {</p> <p>System.out.println ("<<< Committing the Transaction >>>);</p> <p>Ut.commit ();</p> <p>} else {</p> <p>System.out.println ("<<< Rolling Back The Transaction >>);</p> <p>Ut.rollback ();</p> <p>}</p> <p>// We set foo to the value stored in the db</p> <p>RST =</p> <p>Stmt.executeQuery ("SELECT ID, FOO from TestData); if (Rst.next ()) {</p> <p>Foo = Rst.Getint (2);</p> <p>}</p> <p>System.out.println ("foo =" foo ");</p> <p>CONN.CLOSE ();</p> <p>System.out.println ("<<< Done >>>);</p> <p>} catch (exception e) {</p> <p>System.out.print ("dbtest >>");</p> <p>E.PrintStackTrace ();</p> <p>}</p> <p>}</p> <p>Public String getfoo () {return " foo;}</p> <p>}</p> <p>Finally Deploy Your Web App INTO $ CATALINA_HOME / WebApps as a warfile caled dbtest.war.</p> <p>Once Deployed, Point A Browser At http: // localhost: 8080 / dbtest / test.jsp to view the fruits of your hard work.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-117281.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="117281" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.047</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'fIIwAmiL_2B6gGiy31iEbRdUBn9TD1_2FF3Bz3pvhTVng4lPiQc4K6Rh13bw41i_2FEcKYYKZGw9nT_2FR0wxuTWaxCQzw_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>