---
title: "Spring配置之OpenSessionInViewFilter"
author: "kld208"
date: "2012-08-16T17:59:18Z"
tags: []
categories: ["开源软件"]
slug: "spring-opensessioninviewfilter"
draft: false
lastmod: "2012-08-16T17:59:18Z"
id: 1634286
url: "https://kld208.iteye.com/blog/1634286"
---

参考：
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

	<!--Hibernate Open Session in View Filte-->
	<filter>
		<filter-name>hibernateFilter</filter-name>
		<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
		<!-- singleSession默认为true,若设为false则等于没用OpenSessionInView -->
		<init-param>
			<param-name>singleSession</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>hibernateFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>	

```

2，applicationContext.xml配置openSessionInViewInterceptor

```xml

	<bean id="openSessionInViewInterceptor"
		class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

```


三、注意
尽 管Open Session In View看起来还不错，其实副作用不少。看回上面OpenSessionInViewFilter的doFilterInternal方法代码，这个方法实际上是被父类的doFilter调用的，因此，我们可以大约了解的OpenSessionInViewFilter调用流程: 

request(请求)->open session并开始transaction->controller->View(Jsp)->结束transaction并 close session.

一切看起来很正确，尤其是在本地开发测试的时候没出现问题，但试想下如果流程中的某一步被阻塞的话，那在这期间connection就一直被占用而不释放。最有可能被阻塞的就是在写Jsp这步，一方面可能是页面内容大，response.write的时间长，另一方面可能是网速慢，服务器与用户间传输时间久。当大量这样的情况出现时，就有连接池连接不足，造成页面假死现象。

Open Session In View是个双刃剑，放在公网上内容多流量大的网站请慎用