Spring集成Struts的方法
struts要和spring集成,struts就必須能訪問spring的上下文,struts作為web的框架,故要保證web應用程序啟動前裝載了spring的web應用上下文。如果裝載了spring的web上下文,在程序中就可以通過spring提供的WebApplicationContextUtils工具類來訪問該上下文:
ApplicationContext ctx =
WebApplicationContextUtils.getWebApplicationContext(servletContext);
裝載spring上下文的方法有以下幾種:
1、通過web.xml聲明監聽器,在web服務啟動時裝載: (其listener用到context-param)
...................
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
.......................
2、通過web.xml聲明spring提供的ContextLoaderServlet(早期不支持servlet2.4時用):
...................
<servlet>
<servlet-name>contextLoader</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
...................
3、通過struts-config.xml以插件的形式聲明spring提供的ContextLoaderPlugin,就可以向sturts的ActionServlet裝載spring的應用上下文了:
......................
<plug-in className="org.springframework.web.struts.ContextLoaderPlugin">
<set-property property="contextConfigLocation"
value="/WEB-INF/applicationContext.xml"/>
</plug-in>
.........................
集成struts的方法:
1 、使用 org.springframework.web.struts.ActionSupport 類:
這是最簡單的集成struts方法。通過struts的action簡單繼承ActionSupport類便可以直接使用spring上下文。
..............
XXXX xxx=(XXXX)this.getWebApplicationContext().getBean("xxx");
..............
2、使用 org.springframework.web.struts.DelegatingRequestProcessor 類來覆蓋struts的高層處理類RequestProcessor,這就要在struts-config.xml中用controller聲明:
.....................
<action-mappings>
...........
<action path="/login"
type="struts.action.LoginAction"
name="loginForm">
<forward name="success" path="/WEB-INF/main.jsp">
</action>
...........
</action-mappings>
.....................
<controller processorClass="org.springframework.web.struts.DelegatinRequestProcessor"/>
.....................
另外,還要在spring配置文件中,聲明對應某個action的bean,而且bean的name值必須和action的path一致,因為spring容器是根據此bean的name來找到相應的action,然后再進行相應的注入操作的:
................
<bean id="loginService" class="business.LoginServiceImpl">
<property name="name" value="aaaaa"/>
</bean>
<bean name="/login"
class="struts.action.LoginAction">
<property name="loginService">
<ref bean="loginService"/>
</property>
</bean>
................
3、使用 org.springframework.web.struts.AutowiringRequestProcessor 類,它是spring2.0 后加入的。類似DelegatingRequestProcessor,但它的自動完成能力更強。首先也要在struts-config.xml中用<controller>聲明:
........................
<controller processorClass="org.springframework.web.struts.AutowiringRequestProcessor"/>
........................
其他的就照常就得了,它比DelegatingRequestProcessor少了在spring配置中聲明action的bean,它會根據action類名來自動完成注入操作。即Struts的Action中如有某業務類A對象的屬性,又在spring配置文件中聲明了業務類A的Bean,則AutowiringRequestProcessor就會自動將業務類A的Bean注入到Action中。
看上去你好像啥都沒做,而事實上,注入工作已經由AutowiringRequestProcessor自動完成。 這種autowire的注入支持兩種不同的方式,分別是byName和byType,默認是byType。