`
jxb1016
  • 浏览: 22180 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Struts与Spring整合操作步骤。

阅读更多
第一步,向Structs注册Spring插件 。
      为了使Structs能够访问Spring管理的bean,需要注册知晓Spring应用程序环境的Structs插件。在structs-conffig.xml中添加下面的代码来注册插件:
 <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
 	<set-property property="contextConfigLocation"
 	 value="/WEB-INF/classes/applicationContext*.xml"
 	/>
 
 </plug-in>

     ContextLoaderPlugIn加载Spring的上下文环境,这个类来自于Spring2.0 Web Libraries 下的spring-structs.jar包下。我们可以找到该类,拷贝其全限度名称,这样一面手写失误。

第二步:修改Struts的配置文件struts-config.xml中的action type,将控制权交给Spring来管理:
 <action-mappings >
    <action
      attribute="findMeForm"
      input="/form/findMe.jsp"
      name="findMeForm"
      path="/findMe"
      scope="request"
      type="org.springframework.web.struts.DelegatingActionProxy">
      <forward name="result" path="/index.jsp" />
    </action>
  </action-mappings>

    其中org.springframework.web.struts.DelegatingActionProxy来自于自于Spring2.0 Web Libraries 下的spring-structs.jar包下。此类为action的代理,当生成或使用cation对象时候,由Spring提供,并且可以为其注入相关对象等。

第三:在Spring中配置action的对应的信息,也就是在applicationContext.xml中添加如下代码,例如:
<bean name="/findMe" class="com.jxb.struts.action.FindMeAction">
		<property name="storeService" ref="storeService"></property>
</bean>

值得注意的是:那个name属性必须为我们在Struts-config.xml中配置的action的path才行,在Struts2中可以将其配置成对应的name。但这里讲的只是struts1.

第四:在web.xml中添加Srping上下文。
<!-- 装载SPRING上下文 -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>/WEB-INF/classes/applicationContext*.xml</param-value>
  </context-param>
  
  <listener>
  	<listener-class>
  		org.springframework.web.context.ContextLoaderListener
  	</listener-class>
  </listener>

监听器的类在Spring2.0 Web Libraries 下的spring-web.jar包下的org.springframework.web.context中,上下文参数依然是ContextLoaderPlugIn中的属性contextConfigLocation。

由此可知,我们已经完成了两者得到整合,若在action中需要手动获取上下文环境只需要在action里这样:
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServlet().getServletContext());
    IStoreService iss = (IStoreService)ctx.getBean("storeService");


也可以使我们自己的action类继承ActionSupport类,因为该类中可以直接用getWebApplicationContext()方法获取Spring上下文环境。

   总结一下,struts与Srping整合的关键是如何让Struts知道Spring的存在,那么就要把Spring的插件注册到Struts里。如何让Spring帮着管理Action,那么就要将struts配置中的type更改成org.springframework.web.struts.DelegatingActionProxy代理,并且在Srping的配置中配置好对应action的bean信息,如此一来,我们的两者就牵肠挂肚了。为了在容器一启动时候加载Spring的东西,我们就在web.xml中注册了插件的属性参数contextConfigLocation。并且添加了上下文加载之监听器。
   
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics