首页 > 代码库 > hibernate之OpenSessionInView模式代码

hibernate之OpenSessionInView模式代码

import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.Session;
import org.hibernate.Transaction;


import util.HibernateUtil;

public class OpenSessionInViewFilter implements Filter {

    @Override
    public void destroy() {
        

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        // 声明对象
        Session session = null;
        Transaction tx = null;
        // 异常处理
        try {
            // 开启session
            session = HibernateUtil.currentSession();
            // 开始事务
            tx = session.beginTransaction();
// 执行过滤 chain.doFilter(request, response); tx.commit(); // 提交 } catch (Exception e) { if(tx!=null)tx.rollback(); e.printStackTrace(); } finally { System.out.println("关闭session"); HibernateUtil.closeSession(); } } @Override public void init(FilterConfig arg0) throws ServletException { } }

最后更改web.xml文件配置

<filter>
    
  <filter-name>OpenSessionInViewFilter</filter-name>
     
  <filter-class>filter.OpenSessionInViewFilter</filter-class>
  
</filter>
<filter-mapping>

    <filter-name>OpenSessionInViewFilter</filter-name>
   
    <url-pattern>/*</url-pattern>
  
</filter-mapping>

 

hibernate之OpenSessionInView模式代码