Spring和Struts2整合的目的:由容器获取Service或者将Action纳入Spring容器管理(两种整合方式)
分别添加Spring与Struts2的开发环境(jar包与配置文件)
添加Spring的开发环境
Jar包:
1,添加 ${SPRING_HOME}/dist/spring.jar
2,添加 ${SPRING_HOME}/lib/aspectj/*.jar(共2个)
3,添加 ${SPRING_HOME}/lib/cglib/cglib-nodep-2.1_3.jar
4,添加 ${SPRING_HOME}/lib/jakarta-commons/commons-logging.jar
配置文件:
applicationContext.xml,放到Web工程的src文件夹下。
添加Struts2的开发环境
从Struts2的例子程序${Struts2_Home}/apps/struts2-blank-2.1.8.1.war中拷贝出所需要的jar包与配置文件(strtus.xml与web.xml)即可。
整合
1,在web.xml配置监听器(Spring Reference 15.2 Common configuration)
<!--集成Spring-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext*.xml</param-value>
</context-param>
2,拷贝一个用于整合的jar包(与Spring整合用的一个插件)
struts-2.1.8.1/lib/struts2-spring-plugin-2.1.8.1.jar
3,说明:
1,在写Action时要指定 @Controller 与@Scope("prototype")
2,在struts.xml中配置action时,在class属性中写bean的名称
测试
可配置一个Action并部署到Tomcat中测试。
publicclasstestextends ActionSupport {
private UserServiceuserService;
public String execute()throws Exception {
System.out.println(" --- > test.execute()");
ServletContext application = ServletActionContext.getServletContext();
//ApplicationContextac= (ApplicationContext)application.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(application);
userService = (UserService) ac.getBean("userService");
userService.save()
returnthis.SUCCESS;
}
}
上面是Struts2整合Spring的方式,在Action中获取到容器后再找到容器中的对象,Struts.xml配置中还是写全类名,也不需要那个Spring-Struts2插件。这种方式Struts2还是用的自己的IOC容器
还有一种方式,就是Spring整合Struts2,将Action交给容器管理,Struts.xml配置中写Action的名字,需要那个插件,这种方式Struts2使用的是Spring的容器,在Struts.xml中需要配置常量struts.objectFactory=spring
@Controller//交给容器管理
publicclasstestextends ActionSupport {
@Resouce//注入Service
private UserService userService;
public String execute()throws Exception {
userService.save()
returnthis.SUCCESS;
}
}
很显然这一种方式更好。