Papers, tech-Tips, webminars and more
Edit | Attach | New | Raw | Delete | History | Print | Tools

Container Managed Transactions for Servlets and JSP

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. spacer

Copyright © 2014 Atomikos BVBA. Transaction Management for Extreme Transaction Processing and SOA Environments serving ISV, Commercial, OEM and Open Source Markets
Site map RSS ATOM