Spring: OpenSessionInViewInterceptor & OpenSessionInViewFilter Examples

This post on OpenSessionInViewInterceptor vs. OpenSessionInViewFilter gets a lot of views from developers who are searching “OpenSessionInViewFilter” and “OpenSessionInViewFilter”. I’d guess, a lot of them are looking for examples. I don’t want to disappoint anyone so here are example setups of both the filter and the interceptor.

OpenSessionInViewInterceptor

This goes into your action-servlet.xml.

<beans>

<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

<property name="interceptors">
<list>
<ref bean="openSessionInViewInterceptor"/>
</list>
</property>

<property name="mappings">

</bean>

<bean name="openSessionInViewInterceptor"
class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">

<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>

</beans>

OpenSessionInViewFilter

This goes into your web.xml.

<web-app>

<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>

</web-app>

If you are not sure if you need to use the filter or the interceptor, check our post that explains the “>difference between the OpenSessionInViewFilter and the OpenSessionInViewInteceptor. The comments on that page offer some good insight too.