轻松实现线程生命周期内的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

	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值