`

spring和struts如何集成

阅读更多

ApplicationContext是Spring的核心,WebApplicationContext继承自ApplicationContext,首先在Web应用中要初始化WebApplicationContext

,即在web.xml中配置:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- OR USE THE CONTEXTLOADERSERVLET INSTEAD OF THE LISTENER
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
-->

然后对于spring与struts组合的部分,据我所知有三种方法:
1、Spring本身也提供了Struts的相关类,主要使用的有org.springframework.web.struts.ActionSupport,我们只要定义BaseAction继承

AtionSupport,让其他Action继承自BaseAction,就是在BaseAction中调用ActionSupport中getWebApplicationContext()的方法取出

WebApplicationContext,进而取出各种Service。

2、让Spring可以反向控制Struts中的action:
用org.springframework.web.struts.ContextLoaderPlugIn,这是一个Struts的Plug,在Struts启动时加载,对于Action,可以像管理Bean一

样来管理,在struts-config.xml中Action的配置变成类似下面的样子
<action attribute="aForm" name="aForm" path="/aAction" scope="request"

type="org.springframework.web.struts.DelegatingActionProxy">
<forward name="forward" path="forward.jsp" />
</action>
注意type变成了org.springframework.web.struts.DelegatingActionProxy,之后我们需要建立action-servlet.xml(这里只配置action bean

),action-servlet.xml符合Spring的spring-beans.dtd标准,在里面定义类似下面的
<bean name="/aAction" class="com.web.action.Aaction" singleton="false">
<property name="businessService">
<ref bean="businessService"/>
</property>
</bean>

com.web.action.Aaction是Action的实现类,businessService是需要的业务逻辑,Spring会把businessService注入到Action中,在Action中

只要写businessService的get和set方法就可以了,还有一点,action的bean是singleton="false",即每次新建一个实例,这也解决了Struts

中Action的线程同步问题,具体过程是当用户做“/aAction”的HTTP请求(当然应该是“/aAction.do”),Struts会找到这个Action的对应类

org.springframework.web.struts.DelegatingActionProxy,DelegatingActionProxy是个代理类,它会去找action-servlet.xml文件中

“/aAction”对应的真正实现类,然后把它实例化,同时把需要的业务对象注入,然后执行Action的execute方法。

使用了ContextLoaderPlugIn,在struts-config.xml中变成类似这样配置
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation" value="/WEB-INF/applicationContext.xml,/WEB-INF/action-servlet.xml" />
</plug-in>

3、JPetstore例子中并没有使用此方法,而使用了第三种方法。同样只需要动Action。如下:

public abstract class BaseAction extends Action {

  private PetStoreFacade petStore;

 public void setServlet(ActionServlet actionServlet) {
  super.setServlet(actionServlet);
  if (actionServlet != null) {
   ServletContext servletContext = actionServlet.getServletContext();
   WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
   this.petStore = (PetStoreFacade) wac.getBean("petStore");
  }
 }

 protected PetStoreFacade getPetStore() {
  return petStore;
 }

}

分享到:
评论
1 楼 奇林醉 2012-06-13  

相关推荐

Global site tag (gtag.js) - Google Analytics