网上看的较多的也就下面几种
无论哪种第一步把Spring插件添加进去
准备:
可以往Struts的配置文件里添加
<plug-in
className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/classes/applicationContext.xml" />
</plug-in>
或者直接在WEB.XML文件里装载
context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>SpringContextServlet</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
目的多是用ContextLoaderServlet把Spring 配置文件加载了.
1.用ActionSupport支持
可以建立一个BaseAction类EXTENDS ActionSupport
然后可以在类中构造一个getBean的方法
public class BaseAction extends ActionSupport {
protected Object getBean(String id) {
WebApplicationContext ctx = WebApplicationContextUtils
.getWebApplicationContext(this.servlet.getServletContext());
return ctx.getBean(id);
}
}
获得对象,然后可以以后其它所有Struts的ACTION方法中继承BaseAction使用getBean获得对象了,如:
IUserService service = (IUserService) getBean("userService");
注意:这种方法经本人使用,觉得还得稍微改进,比如在Action中用super.save(request,erroes)肯定没用,所以最好是在BaseAction把Action方法覆盖下(打开Eclipse覆盖会发现ActionSuport方法也是继承自Action)
这种方法最简单,也是最好理解的方法,不需要在spring配置中做任何的改变,缺点是它不能获得Spring AOP的优势。还有如果你想替换掉Spring必须重构代码。
2.使用 org.springframework.web.struts.DelegatingRequestProcessor
类来覆盖 Struts 的 RequestProcessor
在Struts配置文件中加入这条:
<controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"/>
然后在Spring中配置:
如 Action中的 path="/reg"
那么applicationContext.xml中
<bean id="RegService" class="com.xuanyuan.RegServiceImpl"/>
<bean name="/reg"
class="com.xuanyuan.regAction">
<property name="RegService">
<ref bean="RegService"/>
</property>
</bean>
Action中的加入代码(BEAN):
private RegService RegService;
public BookService getRegService() {
return RegService;
}
public void setRegService(BookService bookService) {
this.RegService = RegService;
}
配置完成,只要一访问/reg 就会自动填充RegService。
这种方法可以先看struts对于 controller 元素的部分解释:
”processorClass指定负责处理请求的Java类的完整类名。默认值为org.apache.struts.action.RequestProcessor。如果把此项设置为自定义的类,那么应该保证该类扩展了org.apache.struts.action.RequestProcessor类。“
也就是说Struts提供RequestProcessor类是给用户扩展用的,如果你这里用了spring的覆盖你就没办法扩展了,只有扩展Spring提供的了。
3.将动作管理全部交给Spring,
即将struts中所有的type="org.springframework.web.struts.DelegatingActionProxy"
嘿嘿,当然这里有个变种
可以直接把所有action继承DispatchAction,这样就可以不用配置type了(MLDN看到的方法)
然后spring配置文件一样的,传说这是目前最好的方法了。
不过我更喜欢第一种.