这是一个教程,显示如何在使用Apache Struts 1.x开发的Web应用程序中访问在Spring Ioc容器中声明的bean。
下载此Struts 1.x + Spring示例– Struts-Spring-Hibernate-Example.zip
Spring带有针对Spring Ioc容器中声明的访问bean的“特定于Struts的”解决方案。
- 在Struts配置文件中注册Spring的现成Struts插件。
- 更改Struts动作类以扩展Spring的ActionSupport类,该类是Struts动作类的子类。
- ActionSupport提供了一种方便的getWebApplicationContext()方法,供您访问在Spring Ioc容器中声明的bean。
1. Struts + Spring依赖
为了与Struts 1.x集成,Spring需要“ spring-web.jar ”和“ spring-struts.jar ”库。 您可以从Spring网站或Maven下载它。
pom.xml
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-struts</artifactId>
<version>2.0.8</version>
</dependency>
2.注册Struts插件
在您的Struts配置文件(struts-config.xml)中,注册Spring的现成Struts插件–“ ContextLoaderPlugIn ”。
struts-config.xml
<struts-config>
<!-- Spring Struts plugin -->
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/classes/SpringBeans.xml" />
</plug-in>
</struts-config>
“ ContextLoaderPlugIn ”将处理Struts和Spring之间的所有集成工作。 您可以将Spring的bean xml文件加载到“ contextConfigLocation ”属性中。
SpringBeans.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- Beans Declaration -->
<import resource="com/mkyong/customer/spring/CustomerBean.xml"/>
</beans>
3. Spring的ActionSupport
在Struts Action类中,扩展Spring“ ActionSupport ”类,并通过“ getWebApplicationContext() ”方法获取Spring的bean。
CustomerBean.xml
<bean id="customerBo" class="com.mkyong.customer.bo.impl.CustomerBoImpl" >
<property name="customerDao" ref="customerDao" />
</bean>
支撑动作
package com.mkyong.customer.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.ActionSupport;
import com.mkyong.customer.bo.CustomerBo;
import com.mkyong.customer.model.Customer;
public class ListCustomerAction extends ActionSupport{
public ActionForward execute(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response)
throws Exception {
CustomerBo customerBo =
(CustomerBo) getWebApplicationContext().getBean("customerBo");
...
return mapping.findForward("success");
}
}
做完了
翻译自: https://mkyong.com/struts/struts-spring-integration-example/