通过JTOM,用过滤器实现事务控制

利用Jotm和过滤器实现分布式事务管理功能

 

1、下载ow2-jotm-dist-2.2.1-bin.tar.gz,将其目录ow2-jotm-dist-2.2.1\lib的jar拷贝到Tomcat 6.0\lib下

 

2、配置项目下的web.xml

    

<resource-env-ref>   
        <description>DB Connection</description>   
        <resource-env-ref-name>jdbc/myDB</resource-env-ref-name>   
        <resource-env-ref-type>   
            javax.sql.DataSource   
        </resource-env-ref-type>   
    </resource-env-ref>
或者配置Tomcat6的conf中编辑context.xml文件,为Tomcat配置数据源和事务如下如下:
 <Context>
  <WatchedResource>WEB-INF/web.xml</WatchedResource>
  <Resource name="jdbc/myDB" auth="Container"
   type="javax.sql.DataSource" username="test" password="test"
   driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
   url="jdbc:sqlserver://192.168.0.1:1433;databaseName=test"
   maxActive="8" maxIdle="30" maxWait="10000" />
  <Transaction factory="org.objectweb.jotm.UserTransactionFactory"
   jotm.timeout="60" />
  <Manager
   className="org.apache.catalina.session.PersistentManager"
   saveOnRestart="false">
   <Store className="org.apache.catalina.session.FileStore" />
  </Manager>
 </Context> 

3、获取Connection

    

  /**  
     * 获取Connection  
     * @return con  
     */  
    public Connection getConnection()   
    {   
        try  
        {   
            Context ctx = new InitialContext();   
            DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/myDB");   
            return ds.getConnection();   
        }   
        catch (Exception ex)   
        {   
            log.error("Can not get db connection...", ex);   
        }   
        return null;   
    }

 

4、过滤器代码

   

import java.io.IOException;   
  
import javax.naming.Context;   
import javax.naming.InitialContext;   
import javax.servlet.Filter;   
import javax.servlet.FilterChain;   
import javax.servlet.FilterConfig;   
import javax.servlet.ServletException;   
import javax.servlet.ServletRequest;   
import javax.servlet.ServletResponse;   
import javax.servlet.http.HttpServletRequest;   
import javax.servlet.http.HttpServletResponse;   
import javax.transaction.UserTransaction;   
  
import com.autocreate.util.Log;   
  
/**  
 * 登录过滤器  
 *   
 * @author Administrator  
 */  
public class LoginFilter implements Filter   
{   
    private static final String CONTENT_TYPE = "text/html; charset=UTF-8";   
       
    private HttpServletRequest req = null;   
       
    private HttpServletResponse res = null;   
       
    public void init(FilterConfig arg0) throws ServletException   
    {   
    }   
       
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,   
        ServletException   
    {   
        req = (HttpServletRequest)request;   
        res = (HttpServletResponse)response;   
           
        // 设置编码格式   
        req.setCharacterEncoding("UTF-8");   
        res.setContentType(CONTENT_TYPE);   
           
        String requestURI = req.getRequestURI();   
        //Log.getLogger().info("requestURI = " + requestURI);   
           
        // HttpSession session = req.getSession();   
        // PrintWriter out = res.getWriter();   
           
        transactionFilter(request, response, chain, requestURI);   
    }   
       
    /**  
     * 事务过滤器  
     * @param request  
     * @param response  
     * @param chain  
     * @param requestURI  
     * @throws ServletException   
     * @throws IOException   
     */  
    private void transactionFilter(ServletRequest request, ServletResponse response, FilterChain chain,   
        String requestURI) throws IOException,   
        ServletException   
    {   
        String[] params = {"insert", "modify", "delete"};   
        if (checkUrl(requestURI, params))   
        {   
            UserTransaction tx = null;   
            try  
            {   
                Context ctx = new InitialContext();   
                tx = (UserTransaction)ctx.lookup("java:comp/UserTransaction");   
                tx.begin();   
                chain.doFilter(request, response);   
                tx.commit();   
            }   
            catch (Exception e)   
            {   
                try  
                {   
                    res.sendRedirect("manager/AddFailed.jsp");   
                    tx.rollback();   
                }   
                catch (Exception e1)   
                {   
                    Log.getLogger().error("rollback failed...", e1);   
                }   
                Log.getLogger().error("Operation failed...", e);   
            }   
            return;   
        }   
        else  
        {   
            chain.doFilter(request, response);   
        }   
    }   
       
    /**  
     * 验证requestURI的是否含有指定数组里的值  
     * @param requestURI  
     * @param url  
     * @return  
     */  
    private boolean checkUrl(String requestURI, String[] url)   
    {   
        for (int i = 0; i < url.length; i++)   
        {   
            if (requestURI.indexOf(url[i]) != -1)   
            {   
                return true;   
            }   
        }   
        return false;   
    }   
       
    public void destroy()   
    {   
    }   
}  

 

你可能感兴趣的:(sql,tomcat,servlet,jdbc,配置管理)