1. Spring 如何在 WEB 應用中使用 ?
1). 需要額外加入的 jar 包:
spring-web-4.0.0.RELEASE.jar spring-webmvc-4.0.0.RELEASE.jar
2). Spring 的配置文件, 沒有什么不同
3). 如何創建 IOC 容器 ?
①. 非 WEB 應用在 main 方法中直接創建 ②. 應該在 WEB 應用被服務器加載時就創建 IOC 容器:
在 ServletContextListener#contextInitialized(ServletContextEvent sce) 方法中創建 IOC 容器.
③. 在 WEB 應用的其他組件中如何來訪問 IOC 容器呢 ?
在 ServletContextListener#contextInitialized(ServletContextEvent sce) 方法中創建 IOC 容器后, 可以把其放在 ServletContext(即 application 域)的一個屬性中.
④. 實際上, Spring 配置文件的名字和位置應該也是可配置的! 將其配置到當前 WEB 應用的初始化參數中較為合適.
4). 在 WEB 環境下使用 Spring
①. 需要額外加入的 jar 包:
spring-web-4.0.0.RELEASE.jar spring-webmvc-4.0.0.RELEASE.jar
②. Spring 的配置文件, 和非 WEB 環境沒有什么不同
③. 需要在 web.xml 文件中加入如下配置:
<!-- 配置 Spring 配置文件的名稱和位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
<!-- 啟動 IOC 容器的 ServletContextListener --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
2. Spring 如何整合 Struts2 ?
1). 整合目標 ? 使 IOC 容器來管理 Struts2 的 Action!
2). 如何進行整合 ?
①. 正常加入 Struts2
②. 在 Spring 的 IOC 容器中配置 Struts2 的 Action 注意: 在 IOC 容器中配置 Struts2 的 Action 時, 需要配置 scope 屬性, 其值必須為 prototype
<bean id="personAction" class="com.atguigu.spring.struts2.actions.PersonAction" scope="prototype"> <property name="personService" ref="personService"></property> </bean>
③. 配置 Struts2 的配置文件: action 節點的 class 屬性需要指向 IOC 容器中該 bean 的 id
<action name="person-save" class="personAction"> <result>/success.jsp</result> </action>
④. 加入 struts2-spring-plugin-2.3.15.3.jar
3). 整合原理: 通過添加 struts2-spring-plugin-2.3.15.3.jar 以后, Struts2 會先從 IOC 容器中 獲取 Action 的實例.
if (appContext.containsBean(beanName)) { o = appContext.getBean(beanName); } else { Class beanClazz = getClassInstance(beanName); o = buildBean(beanClazz, extraContext); }
新聞熱點
疑難解答