hibernate的OpenSessionInViewFilter用于管理session

Posted 如风105

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hibernate的OpenSessionInViewFilter用于管理session相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

Hibernate→ 《Hibernate程序开发》教材大纲

(转)Hibernate框架基础——Hibernate API及Hibernate主配置文件

Hibernate之Hibernate环境配置

hibernate删除表的方法

Hibernate基础学习—Hibernate相关API介绍

hibernate.properties 与 hibernate.cfg.xml