Spring与Struts2整合:执行流程

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对象。

这里写图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值