集成步骤:
1.和方案1一样需要在web.xml 中配置 spring的 listener
<context-param> <!-- 指定spring的配置文件,默认从web根目录寻找配置文件,我们可以通过spring提供的classpath:前缀指定从类路径下寻找 配置文件有多个的时候可以使用 , 来分隔,ContextLoaderListener 实例化pring容器后,会把它放到Application 范围内 --> <param-name>contextConfigLocation</param-name> <param-value>classpath:beans.xml</param-value> </context-param> <!-- 对Spring容器进行实例化 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
2. 修改struts-config.xml,给struts 配置一个action的处理器,是由spring来实现的,去掉atcion的 type属性,因为这个时候action的实例化是由Spring实例化的
<?xml version="1.0" encoding="ISO-8859-1" ?> <struts-config> <action-mappings> <action path="/list" scope="request" validate="false" > <forward name="list" path="/personlist.jsp"></forward> </action> </action-mappings> <controller> <set-property property="processorClass" value="org.springframework.web.struts.DelegatingRequestProcessor"/> </controller> </struts-config>
3.在beans.xml 中配置 action
<bean name="/list" class="cn.com.xinli.web.action.PersonAction"/>
把action交给spring管理后,我们可以使用依赖注入在action中注入业务层的bean。确保action的path属性值与bean的名称相同。
在struts配置文件中添加进spring的请求控制器,该请法语控制器会先根据action的path属性值到spring容器中寻找跟该属性值同名的bean。如果寻找到即使用该bean处理用户请求 ,如果你也在struts的配置文件中配置了action的type属性,那么只用当spring找不到同名的bean的时候才会使用struts配置文件中的action的type值去实例化action

4.在action中使用依赖注入 (注解方式)得到业务bean
package cn.com.xinli.web.action;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import cn.com.xinli.service.PerService;
public class PersonAction extends Action
{
@Resource PerService perService;
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
//方式1
//得到spring容器实例
//WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(this.getServlet().getServletContext());
//PerService perService=(PerService)ctx.getBean("personService");
//方式2 使用依赖注入
request.setAttribute("persons", perService.getPersons());
return mapping.findForward("list");
}
}
附件中是项目的文件,其中lib目录只别上节内容多了一个 spring-webmvc-struts.jar ,这是spring截获Struts的action来处理请求的处理器的实现