web.xml
<filter>
<filter-name>HelloHibernateFilter</filter-name>
<filter-class>com.xanada.HelloHibernateFilter</filter-class>
</filter> 
<filter-mapping>
<filter-name>HelloHibernateFilter</filter-name>
<url-pattern>/*</url-pattern> //Filter对所有的请求都响应
</filter-mapping> 
HelloHibernateFilter.java
//init在整个servlet的生命周期中只做一次,在这里它初始化了SessionFactory,从而保证了SessionFactory在整个进程中只有一个实例
public void init(FilterConfig filterConfig) 
throws ServletException ...{ 
try ...{
HibernateSessionFactory.init(); 
} catch (HibernateException e) ...{
e.printStackTrace();
}
} 
//session是从DAO中得到的,但是做完一个operation后并不close,而是在整个request完成后在doFilter的finally里面close
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
throws ServletException, IOException ...{ 
try ...{
chain.doFilter(req, res); 
} finally ...{ 
try ...{
HibernateSessionFactory.closeSession(); 
} catch (HibernateException e) ...{
e.printStackTrace();
}
}
} 
其实你若不愿用filter,完全可以把这两段代码放在相应的servlet.init()和servlet.execute()的finally里。
HibernateSessionFactory (可使用hibernate官方的HibernateUtils)
//sessionFactory是一个singleton
private static SessionFactory sessionFactory; 
//init在filter.init()中被调用
public static void init() throws HibernateException 
//currentSession被DAO中被调用
public static Session currentSession() throws HibernateException 
//closeSession在filter.doFilter()的finally中被调用
public static void closeSession() throws HibernateException 
CatDAOImpl
//注意:这里的session用完之后并不close,而只flush一下 
public void delCat(String strCatId) ...{ 
try ...{
Session s = HibernateSessionFactory.currentSession(); 
Object cat = s.load(Cat.class, strCatId);
s.delete(cat);
s.flush(); 
} catch (HibernateException e) ...{
e.printStackTrace();
}
} 
ServletFilter中管理Session
//对Cat的CRUD的封装
public interface CatDAO {
public void creatCat(Cat cat);
public List readCats();
public void updateCat(Cat cat);
public void delCat(String strCatId);
} CatDAO
本文介绍了一种通过Servlet Filter来管理Hibernate Session的方法,确保SessionFactory在应用生命周期内的单一实例,并在每个HTTP请求结束后关闭Session,提高了Session管理的效率及资源利用。

352

被折叠的 条评论
为什么被折叠?



