spring与struts2的整合超级简单的,关键只要把所需的jar包补全就行了。
这些在官网上都有,当然欢迎下载我整理的jar包。
struts2+spring需要的jar包(百度网盘)
整合步骤:
①修改struts.xml配置文件
②修改applicationContext.xml配置文件(没有先创建)
③修改web.xml配置文件
(1)修改struts.xml配置文件
把action配置中的class路径修改为自定义的名称,此名称交给spring的ioc容器管理的对象(交给spring处理)。
修改前:
修改后(自定义名称):
(2)修改applicationContext.xml配置文件(没有先创建)
配置相应的Action的bean,根据struts.xml文件的class的名称。修改自己的项目时有几个action就定义几个,我这里只有一个。
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="login" class="com.LoginAction" scope="prototype"/>
</beans>
(3)修改web.xml配置文件
●为Spring的配置文件路径
●通过监听器初始化Spring的配置环境监听器
基本就是按下面这样配置的,根据自己的项目稍作修改就可以了。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>demox3</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<!-- 配置Struts2框架的核心调度器 -->
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 用于指定Spring的配置文件路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--
服务器启动时,通过监听器初始化Spring的配置环境
监听器,默认加载文件是:/WEB-INF/applicationContext.xml
-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
Unable to instantiate Action异常解决思路
解决思路:
如果没使用spring,struts2.xml中action的路径一定要写完整。
如果使用了spring,配置完还报错的话应该是两个id不一致,注意查看大小写哦!