`

Spring+Struts整合的四种方式

阅读更多

1.在Action中取得BeanFactory对象,然后通过BeanFactory获取业务逻辑对象

在Action中用BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext()); 或ApplicationContext factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());取得BeanFactory,通过factory.getBean(""); 获取实例,调用业务逻辑方法 。 

 

web.xml

 

<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、将业务逻辑对象通过spring注入到Action中,从而避免了在Action类中的直接代码查询,web.xml配置同上

在struts-config.xml文件中配置Action   <action>标签中的type属性需要修改为org.springframework.web.struts.DelegatingActionProxy    DelegatingActionProxy是一个Action,主要作用是取得BeanFactory,然后根据<action>中的path属性值    到IoC容器中取得本次请求对应的Action

 

<action path="/notes"   name="admin"   type="org.springframework.web.struts.DelegatingActionProxy" parameter="method"  scope="prototype"/>

在spring配置文件中需要定义struts的Action,如:<bean name="/notes" class="com.qqhr.lh.struts.Action.NotesAction">    <property name="noteService" ref="notesService"></property>  </bean>

      这里的name名称要与<action>标签的path属性值一致 

      将scope设置为prototype,这样就避免了struts Action的线程安全问题

      必须注入业务逻辑对象

       private NoteService noteService ;

 

 3、使用Spring 的 ActionSupport整合Struts, struts-config.xml添加代码如下:

<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> <set-property property="contextConfigLocation" value="/WEB-INF/applicationContext.xml"/> </plug-in>

  Action里继承 Spring 的 ActionSupport 而不是 Struts Action 类扩展如下:

 使用 getWebApplicationContext() 方法获得一个 ApplicationContext

 

public class UserAction extends ActionSupport{ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ApplicationContext ctx = getWebApplicationContext(); UserService user= (UserService) ctx.getBean("xhf") ; user.load("邢**","北京"); return null ; } }

 

4、使用Spring 的DelegatingRequestProcessor覆盖Struts 的RequestProcessor

   Struts-config.xml文件修改如下:

  

 <action path="/searchSubmit" type="org.springframework.web.struts.DelegatingActionProxy"   input="/notes.do" validate="true" name="notesForm"> 

 <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> <set-property   property="contextConfigLocation" value="/WEB-INF/applicationContext.xml"/> </plug-in>

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics