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

hibernate的OpenSessionInViewFilter用于管理session

时间:2016-06-04 00:29:16      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

OpenSessionInViewFilter.java

用到hibernate框架时可以在每一个项目中都写一个OpenSessionInViewFilter,用于管理session

 

 1 package cn.jbit.auction.web;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.Filter;
 6 import javax.servlet.FilterChain;
 7 import javax.servlet.FilterConfig;
 8 import javax.servlet.ServletException;
 9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 import javax.servlet.http.HttpServletRequest;
12 
13 import org.hibernate.HibernateException;
14 import org.hibernate.Session;
15 import org.hibernate.Transaction;
16 
17 import cn.jbit.auction.dao.HibernateUtil;
18 import cn.jbit.auction.entity.Auctionuser;
19 
20 public class OpenSessionInViewFilter implements Filter {
21 
22     @Override
23     public void destroy() {
24         // TODO Auto-generated method stub
25 
26     }
27 
28     @Override
29     public void doFilter(ServletRequest arg0, ServletResponse arg1,
30             FilterChain arg2) throws IOException, ServletException {
31         HttpServletRequest request=(HttpServletRequest)arg0;
32         
33         Session session = null;
34         Transaction tx = null;
35         try {
36             // 请求到达时,打开Session并启动事务
37             session = HibernateUtil.currentSession();
38             tx = session.beginTransaction();
39             // 执行请求处理链
40             arg2.doFilter(arg0, arg1);
41             // 返回响应时,提交事务
42             tx.commit();
43         } catch (HibernateException e) {
44             e.printStackTrace();
45             if (tx != null)
46                 tx.rollback();
47         } finally {
48             // 关闭session
49             HibernateUtil.closeSession();
50         }
51     }
52 
53     @Override
54     public void init(FilterConfig arg0) throws ServletException {
55         // TODO Auto-generated method stub
56 
57     }
58 
59 }

 

hibernate的OpenSessionInViewFilter用于管理session

标签:

原文地址:http://www.cnblogs.com/jimorulang/p/5557901.html

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