Tip: Con­tain­er-man­aged trans­ac­tions for servlets/JSPs

Every­body knows that EJB con­tain­ers pro­vide con­tain­er-man­aged trans­ac­tions (CMT) as the pre­ferred trans­ac­tion de­mar­ca­tion mech­a­nism. How­ev­er, the same is pos­si­ble for 'sim­ple' servlet/JSP ap­pli­ca­tions that don't have ac­cess to EJB tech­nol­o­gy. This tech tip ex­plains how.

There are at least two al­ter­na­tive ways to let the 'con­tain­er' man­age trans­ac­tions in J2EE web ap­pli­ca­tions:

  1. By us­ing a fil­ter.

  1. By us­ing Spring.

The sec­ond al­ter­na­tive has been the sub­ject of oth­er tech tips and will not be re­peat­ed here.

To en­able con­tain­er-man­aged trans­ac­tions with a fil­ter, it suf­fices to write a fil­ter class as fol­lows:
import com.atomikos.icatch.jta.J2eeUserTransaction;

public class TransactionFilter implements Filter
{
  //Use the Atomikos UserTransaction implementation to start and end
  //the transactions!
  private J2eeUserTransaction utx = new J2eeUserTransaction();
  ... 

 public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain)
 {
    try {

      //start a new transaction for this request
      utx.begin();

      //delegate the request to the next filter, and eventually to the target servlet or JSP
      chain.doFilter(request,response,chain);

      //if no exception happened: commit the transaction
      utx.commit();
    }
    catch( ... ) {
      //analyze exception to dermine of rollback is required or not
      //and then call rollback or commit on utx as appropriate
    }
  }
}

Add this fil­ter on top of every re­quest URL that should be trans­ac­tion­al. Your servlet/JSP or Java code is thus freed from any trans­ac­tion­al source code; all is con­cen­trat­ed in the fil­ter.

As of our re­lease 5.0 this code be­comes even sim­pler, since you can use our new Trans­ac­tionTem­plate class to be­gin and end the trans­ac­tion.
RSS

Comments

Add a comment

Corporate Information

Atomikos Corporate Headquarters
Hoveniersstraat, 39/1, 2800
Mechelen, Belgium

Contact Us

Copyright 2026 Atomikos BVBA | Our Privacy Policy
By using this site you agree to our cookies. More info. That's Fine