Posted on 2011-02-09 18:37
viery 閱讀(1405)
評論(1) 編輯 收藏
轉自王勇老師
筆記
第一種集成方案
原理:在Action中取得BeanFactory對象,然后通過BeanFactory獲取業務邏輯對象
缺點:產生了依賴,spring的類在action中產生了依賴查找。(注意和依賴注入的區別(前者主動))。
1、spring和struts依賴庫配置
* 配置struts
--拷貝struts類庫和jstl類庫
--修改web.xml文件來配置ActionServlet
--提供struts-config.xml文件
--提供國際化資源文件
* 配置spring
--拷貝spring類庫
--提供spring配置文件
2、在struts的Action中調用如下代碼取得BeanFactory
BeanFactoryfactory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
|
使用listener配置beanfactory,將其初始化交給servlet,使其維持在ServletContext中,節省資源。(Listener初始化早于Servlet(Weblogic8除外))
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext-*.xml</param-value>
</context-param>
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
|
3、通過BeanFactory取得業務對象,調用業務邏輯方法
補充:(Struts1.x相關并和Spring集成)
擴展學習:
lJboss的jar包加載順序(根據字母),因此可能使得有些包無法加載。
l使用高級模板創建的jsp文件,由于有
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
------------
<base href="<%=basePath%>" />
|
因此,jsp中的目錄都會從根目錄下查找。
lServlet Listener
Listener是Servlet的監聽器,它可以監聽客戶端的請求、服務端的操作等。通過監聽器,可以自動激發一些操作,比如監聽在線的用戶的數量。當增加一個HttpSession時,就激發sessionCreated(HttpSessionEvent se)方法,這樣就可以給在線人數加1。常用的監聽接口有以下幾個:
ServletContextAttributeListener監聽對ServletContext屬性的操作,比如增加、刪除、修改屬性。
ServletContextListener監聽ServletContext。當創建ServletContext時,激發contextInitialized(ServletContextEvent sce)方法;當銷毀ServletContext時,激發contextDestroyed(ServletContextEvent sce)方法。
HttpSessionListener監聽HttpSession的操作。當創建一個Session時,激發session Created(HttpSessionEvent se)方法;當銷毀一個Session時,激發sessionDestroyed (HttpSessionEvent se)方法。
HttpSessionAttributeListener監聽HttpSession中的屬性的操作。當在Session增加一個屬性時,激發attributeAdded(HttpSessionBindingEvent se) 方法;當在Session刪除一個屬性時,激發attributeRemoved(HttpSessionBindingEvent se)方法;當在Session屬性被重新設置時,激發attributeReplaced(HttpSessionBindingEvent se) 方法。
第二種集成方案
原理:將業務邏輯對象通過spring注入到Action中,從而避免了在Action類中的直接代碼查詢
(客戶端請求---->代理action--->取得beanFactory--->getBean(..)創建action示例--->執行exctute方法)
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
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>
* 必須使用name屬性,name屬性值必須和struts-config.xml文件中<action>標簽的path屬性值一致
* 必須注入業務邏輯對象
* 建議將scope設置為prototype,這樣就避免了struts Action的線程安全問題