现在的位置: 首页 > 综合 > 正文

Spring2.0 集成Struts 2(二)

2013年12月09日 ⁄ 综合 ⁄ 共 2430字 ⁄ 字号 评论关闭

 集成Struts 2的步骤

和Spring集成的目标是什么呢?无非是希望Struts 2的Action定义直接使用Spring IoC的功能,将业务层的Bean注入到Struts 的Action中。用户当然可以简单地在Struts中通过WebApplicationContextUtils.getWebApplicationContext(ServletContext sc)获取Spring容器的Bean,手工将其装配到Action中,但这种“集成”属于低层次的集成,我们要达到的集成目标是:在Spring配置文件中配置Struts Action,并在Struts配置文件中引用。

Spring 2.1目前仅提供了对Struts 1集成的实现方案,尚未对Struts 2提供集成支持。不过Spring或许可以永远卸下这副担子,因为Struts 2已经提供了集成到Spring中的插件,主动投怀送抱了。历史总是让人玩味,在开发初期,Spring不厌其烦,殚精竭虑地为各种著名的框架提供集成的实现方案,等到现在Spring强大之后,各种框架反过来主动提供了集成到Spring的方案。
要将Struts 2集成到Spring中,需要完成以下三个基本步骤:

1.将以下Struts类包添加到类路径下

struts2-core-2.0.6.jar
xwork-2.0.1.jar
ognl-2.6.11.jar
struts2-spring-plugin-2.0.6.jar
freemarker-2.3.8.jar
其中struts2-spring-plugin-2.0.6.jar就是Struts 2提供的用于集成到Spring中的类包。该类包拥有一个struts-plugin.xml配置文件,它定义了一个名为spring的StrutsSpring ObjectFactory的Bean,以便将Action类的管理工作委托给Spring容器进行处理。也就是说,通过StrutsSpringObjectFactory的配置,Struts配置文件就可以直接引用Spring容器中的Bean了。

2.编写Struts配置文件struts.xml

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> ① 通过这个配置指定使用struts-plugin.xml中的StrutsSpringObjectFactory作为 创建Action的工厂类 <constant name= "struts.objectFactory" value="spring" /> </struts>

将其命名为struts.xml文件,并保存在<项目根目录>/src下。

3.配置web.xml

<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <context-param> ①指定Spring配置文件 <param-name>contextConfigLocation</param-name> <param-value>classpath:baobaotao-*.xml,</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> ② 配置Struts2 的过滤器 <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>

我们在类路径下提供了几个Spring配置文件:其中baobaotao-service.xml用于配置业务层Bean,而baobaotao-web.xml用于配置Struts的Action。在①处,通过contextConfigLocation指定Spring配置文件,并配置ContextLoaderListener启动Spring容器。
我们知道Struts 1使用基于Servlet的ActionServlet启动Struts框架,Struts 2使用基于Filer的FilterDispatcher完成相同的工作。FilterDispatcher会自动使用类路径下的struts.xml初始化Struts框架。

通过以上三个基本步骤,我们就将Struts 2集成到Spring中了,但这只是一个基础的空架子,Spring究竟如何配置Struts的Action,Struts又如何引用Spring中配置好的Action,这些具体问题有待于通过实例进行具体的说明。

抱歉!评论已关闭.