今天要解决的就是,保证web项目使用hibernate框架时,始终保持一个Session 对象处于开启状态。
1、创建OpenSessionInViewFilter.java
package com.bdqn.filter;
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.Transaction;
import com.bdqn.dao.HibernateUtil;
public class OpenSessionInViewFilter implements Filter{
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterchain) throws IOException, ServletException {
Transaction tx=null;
try {
//请求到达时,打开Session并开启事务
tx=HibernateUtil.currentSession().beginTransaction();
//执行请求处理链
filterchain.doFilter(request, response);
//返回响应时,提交事务
tx.commit();
} catch (Exception e) {
e.printStackTrace();
if(tx!=null){
tx.rollback();
}
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
2、web.xml中的配置
<filter>
<filter-name>OpenSessionInView</filter-name>
<filter-class>com.bdqn.filter.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>