hibernate监听器 监听session

阅读更多

为了方便的管理session 可以用hibernate监听器

import java.io.IOException;

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 org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateFilter implements Filter {

 private static ThreadLocal hibernateHolder = new ThreadLocal();

 private static SessionFactory factory = null;

 public void destroy() {
 }

 public void doFilter(ServletRequest servletRequest,
   ServletResponse servletResponse, FilterChain filterChain)
   throws IOException, ServletException {
  try {
   filterChain.doFilter(servletRequest, servletResponse);
  } finally {
   Session session = (Session) hibernateHolder.get();
   if (session != null) {
    if (session.isOpen()) {
     session.close();
    }
    hibernateHolder.remove();
   }
  }
 }

 public void init(FilterConfig filterConfig) throws ServletException {
  try {
   Configuration cfg = new Configuration().configure();
   factory = cfg.buildSessionFactory();
  } catch (Exception e) {
   e.printStackTrace();
   throw new ServletException(e);
  }
 }

 public static Session getSession() {
  Session session = (Session) hibernateHolder.get();
  if (session == null) {
   session = factory.openSession();
   hibernateHolder.set(session);
  }
  return session;
 }

}

监听器类,可以替换掉HibernateUtil

另外在web.xml里添加如下配置


    HibernateFilter
    com.schoolstar.util.HibernateFilter


     HibernateFilter
     /*

 

 

ok!

你可能感兴趣的:(hibernate,session,Filter)