Dynamic Web Project 的Struts2项目中引入Spring框架
在Struts2项目中引入Spring框架主要需要以下几个步骤:
- 引入Spring jar包
- 修改web.xml
- 创建bean上下文文件
引入Spring.jar包
Spring相关的文件可以直接在官网上下载,或者使用Struts包里的Spring文件,本博主使用的Struts版本为2.5.17, 在该lib目录下包含了spring jar包, 若要在Struts项目中使用Spring,则需要引入下图选中的jar组件,特别是struts2-spring-plugin-2.5.17,通过该组件,使得Action也支持被Spring容器管理。
将以上文件复制到项目的 WebContent/WEB-INF/lib目录,在Eclipse IDE的 Project Explorer对应的节点 WebContent/WEB-INF/lib,刷新,选中刚引入的spring相关组件, 右击, 在弹出的菜单中选中Build Path,将这些组件添加到BuildPath 中
修改web.xml
在Web.xml中 添加 以下代码行。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:ApplicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
创建bean上下文文件
在src根目录下创建文件 ApplicationContext.xml内容为
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>