码迷,mamicode.com
首页 > Web开发 > 详细

hibernate之OpenSessionInView模式代码

时间:2016-12-08 23:51:34      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:com   开始   on()   res   pen   事务   hiberna   ons   request   

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模式代码

标签:com   开始   on()   res   pen   事务   hiberna   ons   request   

原文地址:http://www.cnblogs.com/AnotherEon001/p/6146932.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!