Spring與Web整合


一 概述

1.整合目的

將所有對象的創建與管理任務交給Spring容器,降低程序的耦合度。

2.整合途徑

將Spring容器注入到Web容器中。

3.具體實現

使用ServletContextListener監聽ServletContext,當ServletContexxt創建時同時創建Spring容器,並將創建完成的容器放到ServletContext即application中,在Web中獲取Spring容器,就可以訪問對象了。ContextLoadListener是ServletContextListener的一個實現類,配置

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

默認情況下,Spring的配置文件只能放在WEB-INF目錄下,名稱為applicationContext.xml,可以在web.xml文件中修改,將配置文件放在src目錄下:

<context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:xxxx.xml</param-value>
</context>

4.獲取Spring容器

WebApplicationContext context=WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());

二 延時加載問題

1.原因

表示層調用Service層方法從數據庫中加載對象,如果Dao層采用了延時加載,返回一個包含null對象的代理,在視圖層訪問對象的詳情時,Service層已經執行完畢,事務已關閉,對象為空,就無法獲取對象的詳情。

2.解決方法

將Session與請求線程綁定,允許在事務關閉以后完成延時加載任務。

3.具體實現

在web.xml中配置:

<filter>
    <filter-name>openSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>opernSessionInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM