Strues+Spring集成

来源:互联网 发布:淘宝为什么没有以纯 编辑:程序博客网 时间:2024/06/05 20:41

  

1,扩展RequestProcessor的配置方式

配置struts-config.xml

<!-- 这句一定要放到<message-resources ../>标签上面 -->

<controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"/> 

这一行代码是告诉Struts用DelegatingRequestProcessor来 代替原来的RequestProcessor,当ActionServlet收到GET或POST的请求,其doGet() 或doPost()会呼叫RequestProcessor类的processActionCreate()方法来处理请求DelegatingRequestProcessor继承了这个类,它重写了processActionCreate()

完成设置这个设置后,Struts会将拦截到的用户请求转发到Spring context下的bean,根据bean的name属性来匹配。而Struts中的action配置则无需配置type属性(即使配置了type属性也 不起任何作用).

获取当前Web应用的Spring容器

WebApplicationContext ctx = 

WebApplicationContextUtils.getWebApplicationContext(servletContext);

配置web.xml

<!-- 装载spring上下文,初始化配置applicationContext.xml,...配置 -->

<!-- 为了让spring容器随应用程序启动而启动-->

   <listener> 

    <listener-class> 

       org.springframework.web.context.ContextLoaderListener 

    </listener-class> 

   </listener> 

 <!--上面配置的类需要一个参数contextConfigLocation,它会自动找到这个

   自动装配ApplicationContext的配置信息

-->

<context-param> 

     <param-name>contextConfigLocation</param-name> 

<!-- 配置多个用逗号分开 -->

     <param-value>

             /WEB-INF/classes/applicationContext.xml,struts-config.xml</param-value> 

</context-param> 

   

除此之外,Spring提供了一个特殊的Servlet类ContextLoaderServlet。该Servlet在启动时,会自动查找WEB-INF/下的applicationContext.xml文件。

当然,为了让ContextLoaderServlet随应用的启动而启动,应将此Servlet配置成load-on-startup的Servlet,load-on-startup的值小一点比较合适,这样可以保证Application- Context更快的初始化。

如果只有一个配置文件,并且文件名为applicationContext.xml,在web.xml文件中增加如下一段即可:

<servlet>

    <servlet-name>context</servlet-name>

    <servlet-class>org.springframework.web.context.ContextLoaderServlet

    </servlet-class>

    <load-on-startup>1</load-on-startup>

</servlet>

如果有多个配置文件,一样使用<context-param>元素来确定多个配置文件。

事实上,不管是ContextLoaderServlet,还是ContextLoaderListener,都依赖于ContextLoader创建ApplicationContext实例。

2,以插件的方式配置  (推荐使用的方式)

配置struts-config.xml

 <!-- 装载配置文件,初始化操作 -->

  <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">

  <set-property property="contextConfigLocation" 

                         value="classpath:applicationContext.xml"/>

  </plug-in> 

<!-- 修改全部的action的type属性,使用代理 -->

<action 

  .....

type="org.springframework.web.struts.DelegatingActionProxy">

</action>

配置了上面的其中一中配置后,就可以在Spring的配置文件(可以不是applicationContext.xml,比如假设这里是action- servlet.xml)中配置用来处理请求的Action bean了。配置的时候需要注意的是Action bean不再需要id属性,而要用name替代id属性,这时name属性的值应与struts-config.xml中配置的Action的path属 性的值相同

还有一种方式是扩展了Action 因此改成继承ActionSupport,很显然这是侵入式的,目前这种方式很少使用

 Action ------- ActionSupport

 DispatchAction-------DispatchActionSupport

原创粉丝点击