Spring和Struts2整合
目的:spring容器管理Action类,代替Servlet
步骤:主要在配置文件
Struts2:
添加支持spring的jar包,
配置<action class="Action类在容器中的id"

Action类:
定义需要容器注入的属性,也就是定义service,service层也要添加调用DAO的属性。并生成get和set方法。
Action:

service:

DAO:
//模拟数据库连接
private String conn;
spring:
1.web.xml配置文件:
alt+/ C 选择ContextLoadListener创建配置
配置文件的位置和名称
classpath:spring文件名.xml
加载容器的监听器
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:app.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.添加Action类的bean:
注入Action类的属性
scope=“prototype” 多例模式
<!-- DAO --> <bean id="testDAO" class="com.hanqi.test.TestDAO"> <property name="conn" value="Oracle"></property> </bean> <!-- service --> <bean id="testService" class="com.hanqi.test.TestService"> <property name="testDAO" ref="testDAO"></property> </bean> <!-- Action --> <!-- scope="prototype"多利模式,Action类的实例不能是单利的 --> <bean id="testID" class="com.hanqi.test.TestAction" scope="prototype"> <property name="testService" ref="testService"></property> </bean>

浙公网安备 33010602011771号