1 28 29 package com.caucho.filters; 30 31 import javax.naming.Context ; 32 import javax.naming.InitialContext ; 33 import javax.naming.NamingException ; 34 import javax.servlet.Filter ; 35 import javax.servlet.FilterChain ; 36 import javax.servlet.FilterConfig ; 37 import javax.servlet.ServletException ; 38 import javax.servlet.ServletRequest ; 39 import javax.servlet.ServletResponse ; 40 import javax.transaction.UserTransaction ; 41 import java.io.IOException ; 42 43 49 public class TransactionFilter implements Filter { 50 53 private UserTransaction _userTransaction; 54 55 58 public void init(FilterConfig config) 59 throws ServletException 60 { 61 try { 62 Context ic = (Context ) new InitialContext (); 63 64 _userTransaction = (UserTransaction ) ic.lookup("java:comp/UserTransaction"); 65 } catch (NamingException e) { 66 throw new ServletException (e); 67 } 68 } 69 70 75 public void doFilter(ServletRequest request, ServletResponse response, 76 FilterChain nextFilter) 77 throws ServletException , IOException 78 { 79 try { 80 _userTransaction.begin(); 81 82 nextFilter.doFilter(request, response); 83 84 _userTransaction.commit(); 85 } catch (ServletException e) { 86 rollback(); 87 throw e; 88 } catch (IOException e) { 89 rollback(); 90 throw e; 91 } catch (RuntimeException e) { 92 rollback(); 93 throw e; 94 } catch (Throwable e) { 95 rollback(); 96 throw new ServletException (e); 97 } 98 } 99 100 103 private void rollback() 104 throws ServletException 105 { 106 try { 107 _userTransaction.rollback(); 108 } catch (Exception e) { 109 throw new ServletException (e); 110 } 111 } 112 113 116 public void destroy() 117 { 118 } 119 } 120 | Popular Tags |