12.Struts2与spring的整合

将struts2-spring-plugin-2.0.14.jar文件拷入lib目录下面。如果不用最好不要拷,因为在这个jar包下面的struts-plugin.xml会自动被加载,为什么会自动被加载,因为在default.properties中有指定。若不用spring而将这个jar包放在lib目录下面,则容易出现错误,因为在加载时会初始化很多东西,需要用到spring中的很多jar包,则此时必须要导入那么jar包才能使程序正常运行。

l          Struts2整合spring的对应规则为,struts的action的class属性对应于spring中bean的id属性,所以在struts中如果用spring来托管action,则action的名字可以任意,只要在spring的bean中有相应的id对应就可以了。另外struts在加载这些配置文件时会自动检测,若是structs中action的class属性即不是一个自定义的action,在spring的配置文件中又找不到对应的bean,则会报错,蛮好!

l          当然在整合ssh2时会出现不使用spring托管action的用法,即不整合spring与struts,此时有两种解决办法。

  1. 不必要拷入struts2-spring-plugin-2.0.14.jar的包。因为这里面没有不涉及到两个框架的整合。
  2. 拷入这个包也并不影响struts,因为虽然在struts2-spring-plugin-2.0.14.jar中的struts-plugin.xml中更改了struts的默认设置,但是这些并不会影响动struts使用非托管的action.因为会有拦截器来自动差别这个action是否被托管。
  3. 简单示例配置如下

l          Struts的action配置

<action name="register" class="userAction" >

<!-- result 的name属性可以不写,不写的话表示为success -->

<result name="invalid.token" type="redirect">/login.jsp</result>

<result>/result.jsp</result>

<result name="input">/index.jsp</result>

<result name="login">/login.jsp</result>

<!--

为这个action指定拦截器,若不指定刚会使用此包的默认拦截器

若指定一个拦截器,则此包的默认拦截器则不会被用于拦截些action

所以若还要使用默认拦截器时必须显示指出,如下:

 -->

<interceptor-ref name="token"></interceptor-ref>

<interceptor-ref name="thirdinterceptor"></interceptor-ref>

<interceptor-ref name="mystack"></interceptor-ref>

<interceptor-ref name="thirdinterceptor"></interceptor-ref>

<interceptor-ref name="thirdinterceptor"></interceptor-ref>

</action>

l          Spring的bean配置

<!--

struts2.x与struts1.x的action的区别很大,在struts1.x中action默认是只实例化一次的。

而在struts2.x中显然只实例化一次是不正确的。所以spring也要保证struts每次向它请求的action是一个新的实例,这很重,

scope="prototype"在此正好适用。事实上spring的bean默认也是只实例化一次的,所以这里特别指定此bean的scope.

 -->

<bean id="userAction" class="edu.yzu.action.UserAction" scope="prototype">

</bean>

 

l          将spring整合到web应用中可先在web.xml中配置

    <context-param>

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

    <param-value>/WEB-INF/applicationContext.xml</param-value>

    </context-param>

    <listener>

        <listener-class>

            org.springframework.web.context.ContextLoaderListener

        </listener-class>

    </listener>

l          在spring与hibernate整合的web运用程序一般会将事务扩大到view层。这在web.xml中的配置如下:

           <filter>

        <filter-name>openSessionInView</filter-name>

        <filter-class>

            org.springframework.orm.hibernate3.support.OpenSessionInViewFilter

        </filter-class>

        <init-param>

            <param-name>singleSession</param-name>

            <param-value>true</param-value>

        </init-param>

        <init-param>

            <param-name>sessionFactoryBeanName</param-name>

            <param-value>sessionFactory</param-value>

        </init-param>

    </filter>

    <filter-mapping>

        <filter-name>openSessionInView</filter-name>

        <url-pattern>/*</url-pattern>

    </filter-mapping>

posted @ 2010-05-03 17:07  沉兮  阅读(814)  评论(0编辑  收藏  举报