HibernateFilter.java

  1. import java.io.IOException;  
  2.  
  3. import javax.servlet.Filter;  
  4. import javax.servlet.FilterChain;  
  5. import javax.servlet.FilterConfig;  
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.ServletRequest;  
  8. import javax.servlet.ServletResponse;  
  9.  
  10. import org.apache.commons.logging.Log;  
  11. import org.apache.commons.logging.LogFactory;  
  12.  
  13. /**  
  14. * 全局Filter 用于自动进行Session和事务的处理  
  15. *   
  16. * @author Administrator  
  17. *   
  18. */  
  19. public class HibernateFilter implements Filter {  
  20.  
  21. // 初始化日志对象  
  22. private static Log log = LogFactory.getLog(HibernateFilter.class);  
  23.  
  24. public void init(FilterConfig config) throws ServletException {  
  25. log.info("servlet filter init.now opening/closing a Session for each request.");  
  26. }  
  27.  
  28. public void doFilter(ServletRequest request, ServletResponse response,  
  29. FilterChain chain) throws IOException, ServletException {  
  30. try {  
  31. //开始一个新的事务,(在这个方法中会默认创建一个新的Session)  
  32. HibernateUtil.beginTransaction();  
  33. //进行事务处理  
  34. chain.doFilter(request, response);  
  35. //提交事务  
  36. HibernateUtil.commitTransaction();  
  37. } catch (ServletException se) {  
  38. log.debug("Rolling back the database transaction.");  
  39. //回滚事务,并关闭Session  
  40. HibernateUtil.rollbackTransaction();  
  41. throw se;  
  42. }catch (IOException e) {  
  43. log.debug("Rolling back the database transaction.");  
  44. // 回滚事务,并关闭Session  
  45. HibernateUtil.rollbackTransaction();  
  46. throw e;  
  47. }finally{  
  48. //关闭Session  
  49. HibernateUtil.closeSession();  
  50. }  
  51.  
  52. }  
  53.  
  54. public void destroy() {  
  55.  
  56. }  
  57.