天天看點

spring4+hibernate4+struts2項目整合的步驟及注意事項

  首先,在整合架構之前,我們需要知道Spring架構在普通Java project和Web project中是略有不同的.

  這個不同地方就在于建立IOC容器執行個體的方式不同,在普通java工程中,可以在main方法中直接建立,可是web工程就不一樣了,在Web項目工程中應該在伺服器加載時就建立IOC容器.也就是說,我們需要web容器能自動加載applicationcontext.xml并初始化.最常用的一種方式,就是在web.xml中添加ContextLoaderListener監聽器.

  先講一下,在WEB環境下,使用Spring的注意事項:

    1. 注意一定要有這兩個jar包,spring-web-4.2.5.RELEASE.jar和spring-webmvc-4.2.5.RELEASE.jar
    2. Spring的配置檔案,和在普通java project的配置檔案相同.
    3. 需要在web.xml中加入以下代碼:
<!-- 配置Spring配置檔案的名稱和位置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
        <!--<param-value>/WEB-INF/applicationContext.xml</param-value>-->
    </context-param>

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

  

  下面介紹ssh整合和步驟,這裡隻做簡單介紹,詳細的步驟,之前的博文中,已經做了詳細的介紹.    

  首先我們選擇先加入Spring,因為Spring需要管理另外兩個架構.

  •   加入Spring
    1.     加入Spring的jar包
    2.     配置web.xml檔案(代碼見上面)
    3.     配置applicationContext.xml
  •   加入hibernate
    1.     加入hibernate的jar包
    2.     配置hibernate.cfg.xml檔案(也可以省略這個配置檔案,這裡選擇保留)
    3.     建立持久化類及對應hbm.xml檔案
    4.     和spring進行整合

         (1) 加入c3p0和mysql的驅動(jar包),這裡選擇使用mysql資料庫和c3p0資料庫池

              在spring中配置,資料源,sessionFactory,聲明式事務.

         (2)   啟動項目,檢查自動生成的表結構

  •   加入struts2(注意額外需要一個struts2-spring-plugin-2.3.16.1.jar,若有重複的jar包,javasist.jar,則删除版本較低的那個jar包)
    1.      導入struts2的jar包
    2.      web.xml中配置struts的filter
    3.      建立struts2的配置檔案struts.xml

   注意:

      在applicationContext.xml中配置Action的bean時,要将scrope設定為prototype,即每次都建立一個新的執行個體.

      在struts.xml中配置Action的class需要指向IOC容器中該Bean的id(以前class的值是該bean的全類名)