OpenSessionInViewFilter的詳細用法,opensessioninview

來源:互聯網
上載者:User

OpenSessionInViewFilter的詳細用法,opensessioninview
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain){try{Session session = ...SessionFactory.getCurrentSeesion(); //得到session對象tx = session.beginTransaction(); //開啟事務chain.doFliter(request,response); //傳遞給下一個tx.commit(); //提交事務}catch (Exception e){//出現異常,復原事務}}簡析:當請求到達時,會首先被此攔截器攔截,當資料經過擷取並在V層顯示完畢後,回到此Filter內部,此時提交事務-->關閉session。二、spring的osiv解決方案OpenSessionInViewFilter [全名:org.springframework.orm.hibernate3.support.OpenSessionInViewFilter]是Spring提供的一個針對Hibernate的一個支援類,其主要意思是在發起一個頁面請求時開啟Hibernate的Session,一直保持這個Session,直到這個請求結束,具體是通過一個Filter來實現的。由於Hibernate引入了Lazy Load特性,使得脫離Hibernate的Session周期的對象如果再想通過getter方法取到其關聯對象的值,Hibernate會拋出一個LazyLoad的Exception。所以為瞭解決這個問題,Spring引入了這個Filter,使得Hibernate的Session的生命週期變長。有兩種方式可以配置實現OpenSessionInView,分別是OpenSessionInViewInterceptor和OpenSessionInViewFilter,功能完全相同,只不過一個在web.xml配置,另一個在application.xml配置而已。這裡採用常用的filter過濾器來實現:<!-- 配置Spring的用於解決懶載入問題的過濾器 -->
<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>*.action</url-pattern>
</filter-mapping>


相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.