struts与spring整合

xiaoxiao2021-03-01  42

struts与spring整合

分类: JAVA 1412人阅读 评论 (0) 收藏 举报

为了在Struts中加载Spring context,需要在struts-config.xml文件中加入如下部分:<struts-config>   <plug-in          className="org.springframework.web.struts.ContextLoaderPlugIn">      <set-property property="contextConfigLocation"          value="/WEB-INF/applicationContext.xml" />   </plug-in> </struts-config>     通过Struts的plug-in在 Struts和Spring 之间提供了良好的结合点。通过plug-in我们实现了Spring context的加载,不过仅仅加载Spring context并没有什么实际的意义,还应该经过配置将Struts的Action交给Spring容器进行管理。<action-mappings>   <action path="/login"              type="org.springframework.web.struts.DelegatingActionProxy"              name="loginForm">       <forward name="success" path="/main.jsp" />       <forward name="failure" path="/login.jsp" /> </action>     在form bean这个节点上与传统的Struts配置没有什么区别,而在Action上面则发生了变化。在传统的action节点上type属性写入action类的完整类名,而和Spring结合后在这点上是使用了Spring提供的 DelegatingActionProxy 作为action的type属性,DelegatingActionProxy 同 样是org.apache.struts.action.Action的一个子类,它将把调用请求转交给真正的Action实现。通过这样的方 式,Spring获得了Action实例的管理权,它将对Action进行调度,并为Struts提供所需的Action实例。这样,就可以将 Action看作是Spring的一个bean,它就可以享受Spring的所有服务,如依赖注入、实例管理、事务管理等。     在applicationContext.xml中相应的配置如下的节点:<beans> .......     <bean name="/login" class="net.xiaxin.action.LoginAction"                            singleton="false">         <property name="userDAO">            <ref bean="userDAOProxy" />         </property>     </bean> </beans>     最后这个bean的配置是关键,这个名为“/login”的bean与Struts中的<action path="/login" ……> …… </action> 节 点相对应,这样,Spring Bean Name与Struts Action Path相关联,当Struts加载对应的Action时,DelegatingActionProxy就根据传入的path属性,在Spring Context寻找对应bean,并将其实例返回给Struts。与此同时,还可以看到,"/login" bean 中包含了一个userDAO 引用,Spring 在运行期将根据配置为其提供userDAO 实例,以及围绕userDAO 的事务管理服务。这样一来,对于Struts 开发而言,我们既可以延续Struts 的开发流程,也可以享受Spring 提供的事务管 理服务。而bean 的另外一个属性singleton="false",指明了Action 的实例获取方式为每次重新创建。这也解决了Struts中令人诟病的线程安全问题。     至此,SS组合已经将Struts MVC以及Spring中的Bean管理、事务管理融为一体。如 果算上userDAO 中的Hibernate 部分,我们就获得了一个全面、成熟、高效、自顶而下的 Web 开发框架。

相关资源:敏捷开发V1.0.pptx
转载请注明原文地址: https://www.6miu.com/read-4200194.html

最新回复(0)