Tip: Container-managed transactions for servlets/JSPs

Everybody knows that EJB containers provide container-managed transactions (CMT) as the preferred transaction demarcation mechanism. However, the same is possible for 'simple' servlet/JSP applications that don't have access to EJB technology. This tech tip explains how.

There are at least two alternative ways to let the 'container' manage transactions in J2EE web applications:

  1. By using a filter.

  1. By using Spring.

The second alternative has been the subject of other tech tips and will not be repeated here.

To enable container-managed transactions with a filter, it suffices to write a filter class as follows:
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 filter on top of every request URL that should be transactional. Your servlet/JSP or Java code is thus freed from any transactional source code; all is concentrated in the filter.

As of our release 5.0 this code becomes even simpler, since you can use our new TransactionTemplate class to begin and end the transaction.

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