Spring與Web整合實例
一 概述
1.整合目的
將所有對象的創(chuàng)建與管理任務(wù)交給Spring容器,降低程序的耦合度。
2.整合途徑
將Spring容器注入到Web容器中。
3.具體實現(xiàn)
使用ServletContextListener監(jiān)聽ServletContext,當ServletContexxt創(chuàng)建時同時創(chuàng)建Spring容器,并將創(chuàng)建完成的容器放到ServletContext即application中,在Web中獲取Spring容器,就可以訪問對象了。ContextLoadListener是ServletContextListener的一個實現(xiàn)類,配置:
<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.原因
視圖層調(diào)用Service的方法從數(shù)據(jù)庫中加載對象,如果Dao實現(xiàn)層采用了延時加載,返回一個包含null對象的代理,在視圖層訪問對象的詳情時,Service層已經(jīng)執(zhí)行完畢,事務(wù)已關(guān)閉,對象為空,就無法獲取對象的詳情。
2.解決方法
將Session與請求線程綁定,允許在事務(wù)關(guān)閉以后完成延時加載任務(wù)。
3.具體實現(xiàn)
在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>
以上這篇Spring與Web整合實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于java關(guān)鍵字this和super的區(qū)別和理解
這篇文章主要給大家介紹了關(guān)于java關(guān)鍵字this和super的區(qū)別和理解的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2021-01-01Spring boot項目中異常攔截設(shè)計和處理詳解
這篇文章主要介給大家紹了關(guān)于Spring boot項目中異常攔截設(shè)計和處理的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習或者使用spring boot具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起看看吧2018-12-12Java數(shù)據(jù)結(jié)構(gòu)之循環(huán)隊列簡單定義與用法示例
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)之循環(huán)隊列簡單定義與用法,簡要描述了循環(huán)隊列的概念、原理,并結(jié)合實例形式分析了java循環(huán)隊列的定義與使用方法,需要的朋友可以參考下2017-10-10