---
title: "Spring配置之OpenSessionInViewFilter"
author: "paynexss"
date: "2016-07-19T15:40:09Z"
tags: ["Hibernate", "Spring", "XML", "openSessionInViewInterceptor"]
categories: ["编程语言"]
slug: "spring-opensessioninviewfilter"
draft: false
lastmod: "2016-07-19T15:40:09Z"
id: 2312178
url: "https://paynexss.iteye.com/blog/2312178"
---

参考：   
OpenSessionInViewFilter作用及配置：http://www.yybean.com/opensessioninviewfilter-role-and-configuration   
http://blog.csdn.net/fooe84/article/details/680449 

主要涉及类：   
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter   
org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor 

一、作用   
    说明一下Open Session in View的作用，就是允许在每次的整个request的过程中使用同一个hibernate session,可以在这个request任何时期lazy loading数据。   
如果是singleSession=false的话，就不会在每次的整个request的过程中使用同一个hibernate session,而是每个数据访问都会产生各自的seesion,等于没有Open Session in View.   
OpenSessionInViewFilter默认是不会对session 进行flush的,并且flush mode 是 never 

spring的OpenSessionInViewFilter过滤器，主要是为了实现Hibernate的延迟加载功能，基于一个请求一个hibernate session的原则。 

二、配置   
它有两种配置方式OpenSessionInViewInterceptor和OpenSessionInViewFilter(具体参看SpringSide)，功能相同，只是一个在web.xml配置，另一个在application.xml配置而已。 

Open Session In View在request把session绑定到当前thread期间一直保持hibernate session在open状态，使session在request的整个期间都可以使用，如在View层里PO也可以lazy loading数据，如 ${ company.employees }。当View 层逻辑完成后，才会通过Filter的doFilter方法或Interceptor的postHandle方法自动关闭session。   
1，web.xml配置OpenSessionInViewFilter 

Xml代码  [![收藏代码](http://kld208.iteye.com/images/icon_star.png)]()

01. &lt;!--Hibernate Open Session in View Filte--&gt;
02. &lt;filter&gt;
03. &lt;filter-name&gt;hibernateFilter&lt;/filter-name&gt;
04. &lt;filter-class&gt;org.springframework.orm.hibernate3.support.OpenSessionInViewFilter&lt;/filter-class&gt;
05. &lt;!-- singleSession默认为true,若设为false则等于没用OpenSessionInView --&gt;
06. &lt;init-param&gt;
07. &lt;param-name&gt;singleSession&lt;/param-name&gt;
08. &lt;param-value&gt;true&lt;/param-value&gt;
09. &lt;/init-param&gt;
10. &lt;/filter&gt;
11. &lt;filter-mapping&gt;
12. &lt;filter-name&gt;hibernateFilter&lt;/filter-name&gt;
13. &lt;url-pattern&gt;/\*&lt;/url-pattern&gt;
14. &lt;/filter-mapping&gt;

2，applicationContext.xml配置openSessionInViewInterceptor 

Xml代码  [![收藏代码](http://kld208.iteye.com/images/icon_star.png)]()

1. &lt;bean id="openSessionInViewInterceptor"
2. class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor"&gt;
3. &lt;property name="sessionFactory" ref="sessionFactory" /&gt;
4. &lt;/bean&gt;

三、注意   
尽 管Open Session In View看起来还不错，其实副作用不少。看回上面OpenSessionInViewFilter的doFilterInternal方法代码，这个方法实际上是被父类的doFilter调用的，因此，我们可以大约了解的OpenSessionInViewFilter调用流程: 

request(请求)-&gt;open session并开始transaction-&gt;controller-&gt;View(Jsp)-&gt;结束transaction并 close session. 

一切看起来很正确，尤其是在本地开发测试的时候没出现问题，但试想下如果流程中的某一步被阻塞的话，那在这期间connection就一直被占用而不释放。最有可能被阻塞的就是在写Jsp这步，一方面可能是页面内容大，response.write的时间长，另一方面可能是网速慢，服务器与用户间传输时间久。当大量这样的情况出现时，就有连接池连接不足，造成页面假死现象。 

Open Session In View是个双刃剑，放在公网上内容多流量大的网站请慎用