Spring与Struts整合时,需要用到两个jar包
spring-web-4.2.4.RELEASE.jar
struts2-spring-plugin-2.3.24.jar
其中,在导入spring-web-4.2.4.RELEASE.jar后,需要在web.xml文件中做如下配置:
<!-- 配置一个监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 指定监听器所读的配置文件的路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
Spring的容器对象applicationContext在整个应用中应该只存在一个,有多个容器对象,会浪费内存。
流程:
spring-web-4.2.4.RELEASE.jar包内封装了一个监听器对象ContextLoaderListener,此对象会在服务器启动创建servletContext对象时根据所配置的路径(默认路径为WEB-INF)自动读取applicationContext.xml文件,并且创建容器对象applicationContext。在服务器销毁servletContext对象时,销毁applicationContext容器对象。
根据servletContext的生命周期可知,在整个应用的运行周期内一个,applicationContext容器对象只有,达到了目标。
注:action生命周期为一次请求,但是整合后Spring管理struts2时默认创建的action为单例模式。所以需要修改Spring中生成action对象时scope为prototype多例模式。
在action动作类中获得Spring容器对象(基本不用,交给Spring创建):
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext( ServletActionContext.getServletContext());
一般都把action交给Spring来创建,在action类中注入service对象。(xml配置方式和注解方式都可以)
在导入struts2-spring-plugin-2.3.24.jar后:
可以把action类的创建交给Spring。此时struts.xml文件中action标签的class属性要写的是applicationContext.xml(Spring配置文件)中所对应的创建action对象的bean标签的id属性。
struts.xml
<action name="*_Customer" class="customerAction" method="{1}">
<result>/jsp/customer/list.jsp</result>
<result name="addCustomerUI">/jsp/customer/add.jsp</result>
</action>
applicationContext.xml
<bean id="customerAction" scope="prototype" class="对应的全限定类名">
<property name="customerService" ref="customerService"> </property>
</bean>
流程:
导入了struts2-spring-plugin-2.3.24.jar包后,每次action的连接访问时,在创建action对象之前,struts2都会先加载6个配置文件(default.properties、struts-default.xml、struts.xml…..)。此时导包后,在加载到struts.xml时,会根读据action标签中的class属性所写的相对应的id值去读取applicationContext.xml文件,从而取到Spring在服务器运行时创建的applicationContext容器对象(web.xml文件中的监听器来监听创建)中的action对象。