zoukankan      html  css  js  c++  java
  • Spring与Struts2整合时action自动注入的问题

       当Struts和Spring框架进行整合时,原本由action实例化对象的过程移交给spring来做(这个过程依赖一个叫struts2-spring-plugin的jar包,这个包主要的功能就是实现刚才那句话,但是MyEclipse自动生成Spring框架时并没有这个jar包,所以需要手动下载后导入)。

      把这个包打开会发现有一个叫struts-plugin.xml的配置文件

    struts-plugin.xml

     1 <struts>
     2     <bean type="com.opensymphony.xwork2.ObjectFactory" name="spring" class="org.apache.struts2.spring.StrutsSpringObjectFactory" />
     3     
     4     <!--  Make the Spring object factory the automatic default -->
     5     <constant name="struts.objectFactory" value="spring" />
     6 
     7     <constant name="struts.class.reloading.watchList" value="" />
     8     <constant name="struts.class.reloading.acceptClasses" value="" />
     9     <constant name="struts.class.reloading.reloadConfig" value="false" />
    10 
    11     <package name="spring-default">
    12         <interceptors>
    13             <interceptor name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/>
    14         </interceptors>
    15     </package>    
    16 </struts>

    这个配置文件中加了<constant name="struts.objectFactory" value="spring" />,所以就不需要在struts.xml中再次添加了。

    ApplicationContext.xml

    1 ...
    2     <bean id="userAction" class="action.UserAction" scope="prototype">
    3         <property name="userDAO" ref="userDAO" />
    4     </bean>
    5 ...

    这里需要注意一下,再Spring配置文件中一定要加上scope这个属性,取值为’prototype’。首先得知道Spring框架生成userAction是单例的,而Structs2框架是多例的,也就是说struts2每请求一个action就会实例化一个action对象,但是Spring只会实例化一次(也就是第一次的数据),这就会导致当多次请求时会出现数据错误的情况。而当我们把scope值设为’prototype’之后,Spring就会跟struts2一样,多少次请求就实例化多少个action对象,互不影响,数据也不会出错。

    struts.xml

    1 ...
    2         <action name="login" class="userAction" method="login">
    3             <result name="admin">/main.jsp</result>
    4             <result name="reader">/reader.jsp</result>
    5             <result name="error">/error.jsp</result>
    6             <result name="input">/userLogin.jsp</result>
    7       </action> 
    8 ...   

    struts.xml中action标签中的class就可以直接写ApplicationContext.xml中bean的id值了,由Spring容器来实例化,但还是由Struts2来管理,因为ApplicationContext.xml中设置了scope属性,也不用考虑数据出错的情况。

  • 相关阅读:
    mapx 32位在win8 64位上使用
    ora01940 无法删除当前连接的用户
    powerdesigner操作
    iis7文件夹 首页设置
    安装vs2013以后,链接数据库总是报内存损坏,无法写入的错误
    【ASP.NET】 中 system.math 函数使用
    Android Bundle类
    android intent 跳转
    vs2012 webservice创建
    Linux中的日志分析及管理
  • 原文地址:https://www.cnblogs.com/baikaizhuliangshui/p/11968550.html
Copyright © 2011-2022 走看看