缺陷:依賴了UserManager
原理:在Action中取得BeanFactory對象,然后通過BeanFactory獲取業務邏輯對象
1、spring和struts依賴庫配置
* 配置struts
--拷貝struts類庫和jstl類庫
--修改web.xml文件來配置ActionServlet
--提供struts-config.xml文件
--提供國際化資源文件
* 配置spring
--拷貝spring類庫
--提供spring配置文件
2、在struts的Action中調用如下代碼取得BeanFatory
BeanFactoryfactory=WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession.getServletContext())
3、通過BeanFactory取得業務對象,調用業務邏輯方法
在web.xml中做如下配置
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext-*.xml,/WEB-INF/applicationContext-*.xml</param-value> 變色部分如果已經在CLASSPATH中配置了可省略
</context-param>
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
servletConetext的一個助手類,可以讀取它àWebApplicationContextUtils
Spring &Hibernate集成方案2
原理:將業務邏輯對象通過spring注入到Action中,從而避免了在Action類中的直接代碼查詢。
1、spring和struts依賴庫配置
* 配置struts
--拷貝struts類庫和jstl類庫
--修改web.xml文件來配置ActionServlet
--提供struts-config.xml文件
--提供國際化資源文件
* 配置spring
--拷貝spring類庫
--提供spring配置文件
2、因為Action需要調用業務邏輯方法,所以需要在Action中提供setter方法,讓spring將業務邏輯注入過來
3、在struts-config.xml文件中配置action
*
<action>標簽中的type屬性需要修改為org.springframework.web.struts.DelegatingActionProxy是一個Action,主要作用是取得BeanFactory,然后根據<action>中的path屬性值到IOC容器中取得本次請求對應的Action
4、在spring配置文件中需要定義struts的Action,如:
<bean name=”/login” class=”com.bjsxt.usermgr.actions.LoginAction”
scope=”prototype”>
<property name=”userManager” ref=”userManager”/>
</bean>
l
必須使用name屬性,name屬性值必須和struts-config.xml文件中<action>標簽的path屬性值一致
l
必須注入業務邏輯對象
l
建議scope設置為prototype,這樣就避免了struts Action的線程安全問題
在struts中應該修改為:
<action path=”/login”
Type=”org.springframework.web.struts.DelegatingActionProxy”
Name=”loginForm”
Scope=”request”
>
</action>
在ApplicationContext中需要做如下修改:
不能有id屬性 而是改成name屬性(路徑應該和struts中的配置的action的path相同)
<bean name=”/login” class=”com.bjsxt.usermgr.action.LoginAction” scope=”prototype”>
<property name=”userManager” ref=”userManagr”/> //變色部分代表從單實例變成多實例
</bean>
--
學海無涯