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
加载容器的监听器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <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” 多例模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <!-- 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> |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步