Spring整合Struts
Spring整合Struts
为什么整合?
使用Spring的IOC功能将业务类注入Action
由Spring创建并管理Action
Spring容器通过Web容器启动(配置监听器ContextLoaderListener即可完成)
步骤:
1、如何启动Spring容器?
配置监听器ContextLoaderListener即可完成,在web.xml中配置
<context-param>
<param-name>contextConfigLocation</param-name><!--
固定的
-->
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--
配置监听器启动Spring容器
-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
2、将创建Action的工作委托给Spring完成,该工作由Spring提供的代理类DelegatingActionProxy实现。
applicationContext.xml:
<!--
name的值必须是Action的path属性值 -->
<bean name="/test"
class="com.aptech.struts.action.TestAction"></bean>
struts-config.xml:
<action
path="/test" type="org.springframework.web.struts.DelegatingActionProxy"
/>
3、将业务对象注入到Action
4、为了能够在Action中访问WEB对象,如ServletContext,则必须将Action配置在单独的文件中,并通过Struts插件(ContextLoaderPlugIn)来加载该文件。
struts-config.xml:
<plug-in
className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property
property="contextConfigLocation"
value="classpath:action-beans.xml"
/>
</plug-in>
得到ServletContext里的spring对象有如下方法:
ServletContext
servletContext =
this.getServlet().getServletContext();
方法一:
{
XmlWebApplicationContext
xmlWebApplicationContext = (XmlWebApplicationContext)
servletContext
.getAttribute(WebApplicationContext
.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
}
方法二:
{
WebApplicationContext
xmlWebApplicationContext =
WebApplicationContextUtils
.getWebApplicationContext(servletContext);
System.out.println(xmlWebApplicationContext);
}
原文:http://www.cnblogs.com/564085446java/p/3608847.html