輕鬆實現線程生命週期內的Session管理

/**
 * 藉助Servlet2.3規範中新引入的Filter機制,輕鬆實現線程生命週期內的Session管理(關於Filter的具體描述,請參考Servlet2.3規範)。
 * Filter的生命週期貫穿了其所覆蓋的Servlet(JSP也可以看作是一種特殊的Servlet)及其底層對象。
 * Filter在Servlet被調用之前執行,在Servlet調用結束之後結束。因此,在Filter 中管理Session 對於Web 程序而言就顯得水到渠成
 * @author wangzyj
 *
 */
public class PersistenceFilter implements Filter {
	protected static ThreadLocal<Session> hibernateHolder = new ThreadLocal<Session>();

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		hibernateHolder.set(HibernateUtil.getCurrentSession());
		try {
			// ......
			chain.doFilter(request, response);
			// ......
		} finally {
			Session sess = (Session) hibernateHolder.get();
			if (sess != null) {
				hibernateHolder.set(null);
				try {
					sess.close();
				} catch (HibernateException ex) {
					throw new ServletException(ex);
				}
			}
		}
	}

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章