溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用Spring怎么對Web項(xiàng)目進(jìn)行整合

發(fā)布時(shí)間:2020-11-27 15:46:56 來源:億速云 閱讀:180 作者:Leah 欄目:編程語言

今天就跟大家聊聊有關(guān)使用Spring怎么對Web項(xiàng)目進(jìn)行整合,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

一 概述

1.整合目的

將所有對象的創(chuàng)建與管理任務(wù)交給Spring容器,降低程序的耦合度。

2.整合途徑

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

3.具體實(shí)現(xiàn)

使用ServletContextListener監(jiān)聽ServletContext,當(dāng)ServletContexxt創(chuàng)建時(shí)同時(shí)創(chuàng)建Spring容器,并將創(chuàng)建完成的容器放到ServletContext即application中,在Web中獲取Spring容器,就可以訪問對象了。ContextLoadListener是ServletContextListener的一個(gè)實(shí)現(xiàn)類,配置:

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

默認(rèn)情況下,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());

二 延時(shí)加載問題

1.原因

視圖層調(diào)用Service的方法從數(shù)據(jù)庫中加載對象,如果Dao實(shí)現(xiàn)層采用了延時(shí)加載,返回一個(gè)包含null對象的代理,在視圖層訪問對象的詳情時(shí),Service層已經(jīng)執(zhí)行完畢,事務(wù)已關(guān)閉,對象為空,就無法獲取對象的詳情。

2.解決方法

將Session與請求線程綁定,允許在事務(wù)關(guān)閉以后完成延時(shí)加載任務(wù)。

3.具體實(shí)現(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>

看完上述內(nèi)容,你們對使用Spring怎么對Web項(xiàng)目進(jìn)行整合有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI