前提:
必须在Web应用启动时,创建Spring的ApplicationContext实例
方式:
1、采用ContextLoaderListener来创建ApplicationContext:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-config/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
2、采用ContextLoaderPlugIn来创建ApplicationContext
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation" value="/WEB-INF/config/sale.xml" />
</plug-in>
补充:
如果web容器的版本较低,不支持监听器,可以采用如下方式:此时,要设置load-on-startup
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-config/applicationContext.xml
</param-value>
</context-param>
<servlet>
<servlet-name>springContextLoaderServlet</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
方式一:通过Spring的ActionSupport类
ActionSupport类:
知道ApplicationContext的获得方式。
步骤:
1、Action直接继承ActionSupport
2、使用ApplicationContext ctx = getWebApplicationContext();取得Spring上下文
3、取得相应Bean
注意:有可能需要替换commons-attributes-compiler.jar包。
优点:
简单
缺点:
耦合高
违反IOC
方式二:通过Spring的DelegatingActionProxy类
步骤:
1、Action中,使用IOC获得服务
2、配置struts-config.xml
<action path="/somepath" type="org.springframework.web.struts.DelegatingActionProxy"/>
3、在Spring配置文件中
<bean name="/somepath" class="SomeAction">
<property name="service"><ref bean=""/>
</bean>
注意,要用bean name命名。
/somepath:Action的path
优点:
不使用Spring api编写 Action
利用了IOC装配。
可以利用容器的scope="prototype"来保证每一个请求有一个单独的Action来处理,
避免struts中Action的线程安全问题。
缺点:
struts配置文件中,所有path都映射到同一个代理类
方式三:通过Spring的DelegatingRequestProcessor类
步骤:
1、Action中,使用IOC获得服务
2、配置struts-config.xml
<controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor" />
3、在Spring配置文件中
<bean name="/somepath" class="SomeAction">
<property name="service"><ref bean=""/>
</bean>
补充:
ServletContext sc = this.getServlet().getServletContext();
WebApplicationContext ac =
(WebApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
小结:
Spring与Struts整合方式只有两种:
(1)由Spring容器来管理Action(方式二,方式三)
(2)Action处于容器之外(方式一)
Spring与Struts整合
最新推荐文章于 2025-08-12 10:06:30 发布