零侵入实现Strtus1.3和Spring的集成

以前都是用webwork,最近因为遗留项目的维护,捣腾起struts1.x,原先的代码到处充斥着ApplicationContext.getBean的代码,实在没法容忍,上网找了struts和spring集成的例子,基本上都是struts1.3以前版本的代码,很不优雅。struts1.3和之前版本相比,使用command-chain来处理请求,有点类似于webwork的拦截器,下面介绍下整个实现思路,欢迎批评指正。

1、首先需要一个ServletContextListener,用于获取Spring的ApplicationContext实例(使用Quake Wang的jert的代码),具体请参考附件源码

2、定义ComponentAutowireInterceptor实现ActionCommon接口,以实现spring bean的注入,这里为了方便,直接从CreateAction继承:
[code]
/**
* $Revision: 1.0 $
* Created: 2007-8-17
* $Date: 2007-8-17 $
*
* Author: Keven Chen
*/
package struts.demo.command;

import org.apache.struts.action.Action;
import org.apache.struts.chain.commands.servlet.CreateAction;
import org.apache.struts.chain.contexts.ActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.comwave.webui.core.container.Application;

/**
* @author Keven Chen
* @version $Revision 1.0 $
*
*/
public class ComponentAutowireInterceptor extends CreateAction {

protected Action createAction(ActionContext context, String type) throws Exception {
Action action = super.createAction(context, type);
if(action !=null){
Application.getInstance().getContainer().autowireComponent(action);
System.out.println("装配Action");
}
return action;
}

}
[/code]

3、配置web.xml和chain-config.xml配置片段(完整配置请参考附件代码)

web.xml
[code]
....
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext*.xml</param-value>
</context-param>

<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<listener> <listener-class>com.comwave.webui.core.web.listener.DefaultApplicationSetupListener</listener-class>
</listener>

<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>struts/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>chainConfig</param-name>
<param-value>struts/chain-config.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
....
[/code]
chain-config.xml
[code]
....
<!--command className="org.apache.struts.chain.commands.servlet.CreateAction"/-->

<command className="struts.demo.command.ComponentAutowireInterceptor"/><!--替换原先的CreateAction-->
....
[/code]

Struts的Action无需实现任何接口,也不需要特别的配置,就可以自动实现spring bean的注入。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值