1 16 package org.directwebremoting.hibernate; 17 18 import java.lang.reflect.Method ; 19 20 import javax.servlet.ServletContext ; 21 22 import org.directwebremoting.AjaxFilter; 23 import org.directwebremoting.AjaxFilterChain; 24 import org.directwebremoting.WebContextFactory; 25 import org.directwebremoting.util.Logger; 26 import org.hibernate.Session; 27 import org.hibernate.SessionFactory; 28 import org.hibernate.Transaction; 29 30 36 public class H3SessionAjaxFilter implements AjaxFilter 37 { 38 41 public Object doFilter(Object object, Method method, Object [] params, AjaxFilterChain chain) throws Exception 42 { 43 ServletContext context = WebContextFactory.get().getServletContext(); 44 SessionFactory sessionFactory = (SessionFactory) context.getAttribute(ATTRIBUTE_SESSION); 45 46 Transaction transaction = null; 47 if (sessionFactory != null) 48 { 49 Session session = sessionFactory.getCurrentSession(); 50 transaction = session.beginTransaction(); 51 } 52 else 53 { 54 log.error("SessionFactory not initialized for this web application. Use: H3SessionAjaxFilter.setSessionFactory(servletContext, sessionFactory);"); 55 } 56 57 Object reply = chain.doFilter(object, method, params); 58 59 if (transaction != null) 60 { 61 transaction.commit(); 62 } 63 64 return reply; 65 } 66 67 73 public static void setSessionFactory(ServletContext context, SessionFactory sessionFactory) 74 { 75 context.setAttribute(ATTRIBUTE_SESSION, sessionFactory); 76 } 77 78 86 public static Session getCurrentSession(ServletContext context) 87 { 88 SessionFactory sessionFactory = (SessionFactory) context.getAttribute(ATTRIBUTE_SESSION); 89 if (sessionFactory == null) 90 { 91 return null; 92 } 93 94 return sessionFactory.getCurrentSession(); 95 } 96 97 100 private static final Logger log = Logger.getLogger(H3SessionAjaxFilter.class); 101 102 105 protected static final String ATTRIBUTE_SESSION = "org.directwebremoting.hibernate.SessionFactory"; 106 } 107 | Popular Tags |