Struts2+Spring3+Hibernate——整合byMaven

在平時的JavaEE開發中,爲了可以用最快的速度開發項目,通常都會選擇使用Struts2,SpringMVC,Spring,Hibernate,MyBatis這些開源框架來開發項目,而這些框架通常不是單獨使用的,常常是Struts2+Spring3+Hibernate、SpringMVC+Spring+Hibernate、SpringMVC+Spring+Mybatis這幾種組合中的一種,也就是多個框架配合起來使用。今天來總結一下如何使用Maven搭建Struts2+Spring3+Hibernate4的整合開發環境。 html

1、創建Maven工程

第一步: java

  

第二步: mysql

  

第三步: web

  

  建立好的項目以下圖所示: spring

  

第四步: sql

  

  注意:這裏的JDK要選擇默認的,這樣別人在使用的時候,如何JDk不一致的話也不會出錯,以下圖所示: 數據庫

  

第五步: express

  建立Maven標準目錄 
    src/main/java 
    src/main/resources
    src/test/java 
    src/test/resources apache

  

第六步:   瀏覽器

  發佈項目:Maven install     

  清除編譯過的項目:Maven clean

  

  Maven install命令執行結果以下:

  

  OK,Maven工程建立成功!

2、搭建Spring3開發環境

2.一、下載Spring3須要的jar包

    1.spring-core

    2.spring-context

    3.spring-jdbc

    4.spring-beans

    5.spring-web

    6.spring-expression

    7.spring-orm

  在pom.xml中編寫Spring3須要的包,maven會自動下載這些包以及相關的依賴jar包。

 1 <!-- spring3 -->
 2         <dependency>
 3             <groupId>org.springframework</groupId>
 4             <artifactId>spring-core</artifactId>
 5             <version>3.1.2.RELEASE</version>
 6         </dependency>
 7         <dependency>
 8             <groupId>org.springframework</groupId>
 9             <artifactId>spring-context</artifactId>
10             <version>3.1.2.RELEASE</version>
11         </dependency>
12         <dependency>
13             <groupId>org.springframework</groupId>
14             <artifactId>spring-jdbc</artifactId>
15             <version>3.1.2.RELEASE</version>
16         </dependency>
17         <dependency>
18             <groupId>org.springframework</groupId>
19             <artifactId>spring-beans</artifactId>
20             <version>3.1.2.RELEASE</version>
21         </dependency>
22         <dependency>
23             <groupId>org.springframework</groupId>
24             <artifactId>spring-web</artifactId>
25             <version>3.1.2.RELEASE</version>
26         </dependency>
27         <dependency>
28             <groupId>org.springframework</groupId>
29             <artifactId>spring-expression</artifactId>
30             <version>3.1.2.RELEASE</version>
31         </dependency>
32         <dependency>
33             <groupId>org.springframework</groupId>
34             <artifactId>spring-orm</artifactId>
35             <version>3.1.2.RELEASE</version>
36         </dependency>

2.二、編寫Spring配置文件

  在src/main/resources目錄下建立一個spring.xml文件,以下圖所示:

  

  spring.xml文件的內容以下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans" 
 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 4 xmlns:context="http://www.springframework.org/schema/context" 
 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 
 6 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
 7 http://www.springframework.org/schema/context 
 8 http://www.springframework.org/schema/context/spring-context-3.0.xsd
 9 ">
10 
11     <!-- 引入屬性文件,config.properties位於src/main/resources目錄下 -->
12     <context:property-placeholder location="classpath:config.properties" />
13 
14     <!-- 自動掃描dao和service包(自動注入) -->
15     <context:component-scan base-package="me.gacl.dao,me.gacl.service" />
16 
17 </beans>


  在src/main/resources目錄下建立一個config.properties文件,以下圖所示:

  

  config.properties文件主要是用來編寫一些系統的配置信息,例如數據庫鏈接信息,config.properties文件中的內容暫時先不編寫,等整合到Hibernate時再編寫具體的數據庫鏈接信息。

2.三、編寫單元測試

  首先,在src/main/java中建立me.gacl.service包,在包中編寫一個 UserServiceI 接口,以下圖所示:

  

  代碼以下:

 1 package me.gacl.service;
 2 
 3 /**
 4  * 測試
 5  * @author gacl
 6  *
 7  */
 8 public interface UserServiceI {
 9 
10     /**
11      * 測試方法
12      */
13     void test();
14 }


  而後,在src/main/java中建立me.gacl.service.impl包,在包中編寫UserServiceImpl實現類,以下圖所示:

  

  代碼以下:


 1 package me.gacl.service.impl;
 2 
 3 import org.springframework.stereotype.Service;
 4 
 5 import me.gacl.service.UserServiceI;
 6 //使用Spring提供的@Service註解將UserServiceImpl標註爲一個Service
 7 @Service("userService")
 8 public class UserServiceImpl implements UserServiceI {
 9 
10     @Override
11     public void test() {
12         System.out.println("Hello World!");
13     }
14 
15 }


  進行單元測試時須要使用到Junit,因此須要在pom.xml文件中添加Junit的jar包描述,以下:

1         <!-- Junit -->
2         <dependency>
3             <groupId>junit</groupId>
4             <artifactId>junit</artifactId>
5             <version>4.12</version>
6             <scope>test</scope>
7         </dependency>


  <scope>test</scope>這裏的test表示測試時編譯src/main/test文件夾中的文件,等發佈的時候不編譯。 最後,在src/main/test中建立me.gacl.test包,在包中編寫 TestSpring類,以下圖所示:

  

代碼以下:


 1 package me.gacl.test;
 2 
 3 import me.gacl.service.UserServiceI;
 4 
 5 import org.junit.Test;
 6 import org.springframework.context.ApplicationContext;
 7 import org.springframework.context.support.ClassPathXmlApplicationContext;
 8 
 9 public class TestSpring {
10 
11     @Test
12     public void test(){
13         //經過spring.xml配置文件建立Spring的應用程序上下文環境
14         ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring.xml");
15         //從Spring的IOC容器中獲取bean對象
16         UserServiceI userService = (UserServiceI) ac.getBean("userService");
17         //執行測試方法
18         userService.test();
19     }
20 }


  JUnit Test運行,結果如圖所示:

  

2.四、在web.xml中配置Spring監聽器

1 <!-- Spring監聽器 -->
2     <listener>
3         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
4     </listener>
5     <!-- Spring配置文件位置 -->
6     <context-param>
7         <param-name>contextConfigLocation</param-name>
8         <param-value>classpath:spring.xml</param-value>
9     </context-param>


  在tomcat服務器中進行測試,先執行【Maven install】命令發佈項目,而後將SSHE項目部署到tomcat服務器,最後啓動tomcat服務器

  

  tomcat服務器啓動的過程當中沒有出現報錯,輸入地址:http://localhost:8080/SSHE/ 可以正常進行訪問,就說明Spring3的開發環境搭建成功,以下圖所示:

  

  測試經過,Spring3開發環境搭建成功!

3、搭建Struts2開發環境並整合Spring3

3.一、下載Struts2須要的jar包

  1.strtus2-core 
  2.struts2-spring-plugin(struts2和Spring整合時須要使用到的插件)
  3.struts2-convention-plugin(使用了這個插件以後,就能夠採用註解的方式配置Struts的Action,免去了在struts.xml中的繁瑣配置項)

  4.struts2-config-browser-plugin(config-browser-plugin插件不是必須的,可是使用了這個插件以後,就能夠很方便的瀏覽項目中的全部action及其與 jsp view的映射)

  在pom.xml文件中編寫Struts2所須要的jar包,Maven會自動下載這些包


 1 <!-- Struts2的核心包 -->
 2         <dependency>
 3             <groupId>org.apache.struts</groupId>
 4             <artifactId>struts2-core</artifactId>
 5             <version>2.3.16</version>
 6             <!--
 7             這裏的 exclusions 是排除包,由於 Struts2中有javassist,Hibernate中也有javassist,
 8             因此若是要整合Hibernate,必定要排除掉Struts2中的javassist,不然就衝突了。
 9             <exclusions>
10                 <exclusion>
11                     <groupId>javassist</groupId>
12                     <artifactId>javassist</artifactId>
13                 </exclusion>
14             </exclusions> 
15             -->
16         </dependency>
17         <!-- convention-plugin插件,使用了這個插件以後,就能夠採用註解的方式配置Action -->
18         <dependency>
19             <groupId>org.apache.struts</groupId>
20             <artifactId>struts2-convention-plugin</artifactId>
21             <version>2.3.20</version>
22         </dependency>
23         <!--config-browser-plugin插件,使用了這個插件以後,就能夠很方便的瀏覽項目中的全部action及其與 jsp view的映射 -->
24         <dependency>
25             <groupId>org.apache.struts</groupId>
26             <artifactId>struts2-config-browser-plugin</artifactId>
27             <version>2.3.20</version>
28         </dependency>
29         <!-- Struts2和Spring整合插件 -->
30         <dependency>
31             <groupId>org.apache.struts</groupId>
32             <artifactId>struts2-spring-plugin</artifactId>
33             <version>2.3.4.1</version>
34         </dependency>


  

3.二、編寫Struts.xml配置文件

  在src/main/resources目錄下建立一個struts.xml文件,以下圖所示:

  

  struts.xml文件中的內容以下:


 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
 3 <struts>
 4 
 5     <!-- 指定由spring負責action對象的建立 -->
 6     <constant name="struts.objectFactory" value="spring" />
 7     <!-- 全部匹配*.action的請求都由struts2處理 -->
 8     <constant name="struts.action.extension" value="action" />
 9     <!-- 是否啓用開發模式(開發時設置爲true,發佈到生產環境後設置爲false) -->
10     <constant name="struts.devMode" value="true" />
11     <!-- struts配置文件改動後,是否從新加載(開發時設置爲true,發佈到生產環境後設置爲false) -->
12     <constant name="struts.configuration.xml.reload" value="true" />
13     <!-- 設置瀏覽器是否緩存靜態內容(開發時設置爲false,發佈到生產環境後設置爲true) -->
14     <constant name="struts.serve.static.browserCache" value="false" />
15     <!-- 請求參數的編碼方式 -->
16     <constant name="struts.i18n.encoding" value="utf-8" />
17     <!-- 每次HTTP請求系統都從新加載資源文件,有助於開發(開發時設置爲true,發佈到生產環境後設置爲false) -->
18     <constant name="struts.i18n.reload" value="true" />
19     <!-- 文件上傳最大值 -->
20     <constant name="struts.multipart.maxSize" value="104857600" />
21     <!-- 讓struts2支持動態方法調用,使用歎號訪問方法 -->
22     <constant name="struts.enable.DynamicMethodInvocation" value="true" />
23     <!-- Action名稱中是否仍是用斜線 -->
24     <constant name="struts.enable.SlashesInActionNames" value="false" />
25     <!-- 容許標籤中使用表達式語法 -->
26     <constant name="struts.tag.altSyntax" value="true" />
27     <!-- 對於WebLogic,Orion,OC4J此屬性應該設置成true -->
28     <constant name="struts.dispatcher.parametersWorkaround" value="false" />
29 
30     <package name="basePackage" extends="struts-default">
31 
32
33     </package>
34 
35 </struts>


3.三、在web.xml中配置Struts2的過濾器


 1 <!-- Struts2的核心過濾器配置 -->
 2     <filter>
 3         <filter-name>struts2</filter-name>
 4         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
 5     </filter>
 6     <!-- Struts2過濾器攔截全部的.action請求 -->
 7     <filter-mapping>
 8         <filter-name>struts2</filter-name>
 9         <url-pattern>*.action</url-pattern>
10     </filter-mapping>


 3.四、編寫測試

  首先,在src/main/java中建立me.gacl.action包,在包中編寫一個 TestAction類,以下圖所示:

  

  代碼以下:

 1 package me.gacl.action;
 2 
 3 import me.gacl.service.UserServiceI;
 4 
 5 import org.apache.struts2.convention.annotation.Action;
 6 import org.apache.struts2.convention.annotation.Namespace;
 7 import org.apache.struts2.convention.annotation.ParentPackage;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 
10 @ParentPackage("basePackage")
11 @Action(value="strust2Test")//使用convention-plugin插件提供的@Action註解將一個普通java類標註爲一個能夠處理用戶請求的Action,Action的名字爲struts2Test
12 @Namespace("/")//使用convention-plugin插件提供的@Namespace註解爲這個Action指定一個命名空間
13 public class TestAction {
14     
15     /**
16      * 注入userService
17      */
18     @Autowired
19     private UserServiceI userService;
20 
21     /**
22      * http://localhost:8080/SSHE/strust2Test!test.action
23      * MethodName: test
24      * Description: 
25      * @author xudp
26      */
27     public void test(){
28         System.out.println("進入TestAction");
29         userService.test();
30     }
31 }


  這裏使用@Autowired註解將userService注入到UserAction中。

  測試Struts2的開發環境是否搭建成功,先執行【Maven install】操做,而後部署到tomcat服務器,最後啓動tomcat服務器運行,

  輸入訪問地址:http://localhost:8080/SSHE/strust2Test!test.action,訪問結果以下:

  

  測試經過,Struts2的開發環境搭建並整合Spring成功!這裏提一下遇到的問題,我執行完Maven install命令以後,從新發布到tomcat服務器運行,第一次運行時出現了找不到action的404錯誤,後來就先執行Maven clean,而後clean一下項目,再執行Maven install命令從新編譯項目,而後再發布到tomcat服務器中運行,此次就能夠正常訪問到action了,使用Maven老是會遇到一些奇怪的問題,好在憑藉着一些平時積累的解決問題的經驗把問題解決了。

4、搭建Hibernate4開發環境並整合Spring3

4.一、下載Hibernate4須要的jar包

  1.hibernate-core

  在pom.xml文件中編寫Hibernate4所須要的jar包,Maven會自動下載這些包。


1 <!-- hibernate4 -->
2         <dependency>
3             <groupId>org.hibernate</groupId>
4             <artifactId>hibernate-core</artifactId>
5             <version>4.1.7.Final</version>
6         </dependency>


  

  注意:必定要排除掉Struts2中的javassist,不然就衝突了。

4.二、添加數據庫驅動jar包

  咱們知道,Hibernate是用於和數據庫交互的,應用系統全部的CRUD操做都要經過Hibernate來完成。既然要鏈接數據庫,那麼就要使用到相關的數據庫驅動,因此須要加入數據庫驅動的jar包,根據自身項目使用的數據庫在pom.xml文件中編寫相應的數據庫驅動jar:

  MySQL數據庫驅動jar:

1 <!-- mysql驅動包 -->
2         <dependency>
3             <groupId>mysql</groupId>
4             <artifactId>mysql-connector-java</artifactId>
5             <version>5.1.34</version>
6         </dependency>

  SQLServer數據庫驅動jar:

1 <!-- SQLServer數據庫驅動包 -->
2         <dependency>
3             <groupId>net.sourceforge.jtds</groupId>
4             <artifactId>jtds</artifactId>
5             <version>1.3.1</version>
6         </dependency>


  這裏要說一下使用Maven管理Oracle JDBC驅動的問題了,正常狀況下,Maven在下載 oracle數據庫驅動時會出錯,以下圖所示:

  

  這是因爲Oracle受權問題,Maven3不提供Oracle JDBC driver,爲了在Maven項目中應用Oracle JDBC driver,必須手動添加到本地倉庫。

  解決辦法:先從網上下載Oracle的驅動包,而後經過Maven命令放到本地庫中去:

  安裝命令:

mvn install:install-file -Dfile={Path/to/your/ojdbc.jar} -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.1.0 -Dpackaging=jar

  例如把位於F:\oracle驅動\ojdbc6.jar添加到本地倉庫中

  

  執行命令:

mvn install:install-file -Dfile=F:/oracle驅動/ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.1.0 -Dpackaging=jar

  以下圖所示:
  

  而後在pom.xml文件中編寫ojdbc6.jar包的<dependency>信息,以下所示:

1 <!--Oracle數據庫驅動包,針對Oracle11.2的ojdbc6.jar -->
2         <dependency>  
3              <groupId>com.oracle</groupId>  
4              <artifactId>ojdbc6</artifactId>  
5              <version>11.2.0.1.0</version>  
6         </dependency>


  因爲咱們已經將ojdbc6.jar包加入到本地倉庫中了,所以此次能夠正常使用針對Oracle數據庫的驅動包了。以下圖所示:

  

4.三、添加數據庫鏈接池jar包

  在平時開發中,咱們通常都會使用數據庫鏈接池,應用系統初始化時,由數據庫鏈接池向數據庫申請必定數量的數據庫鏈接,而後放到一個鏈接池中,當須要操做數據庫時,就從數據庫鏈接池中取出一個數據庫鏈接,經過從鏈接池中獲取到的數據庫鏈接對象鏈接上數據庫,而後進行CRUD操做,關於數據庫鏈接池的選擇,經常使用的有DBCP,C3P0和Druid,這裏咱們使用Druid做爲咱們的數據庫鏈接池。這三種鏈接池各自有各自的特色,本身熟悉哪一個就用哪一個,蘿蔔白菜,各有所愛。

  在pom.xml文件中編寫Druid的jar包,Maven會自動下載,以下:

1 <!--Druid鏈接池包 -->
2         <dependency>
3             <groupId>com.alibaba</groupId>
4             <artifactId>druid</artifactId>
5             <version>1.0.12</version>
6         </dependency>

 

4.四、添加aspectjweaver包

  使用Spring的aop時須要使用到aspectjweaver包,因此須要添加aspectjweaver包,在pom.xml文件中添加aspectjweaver的jar包,Maven會自動下載,以下:

1 <!--aspectjweaver包 -->
2         <dependency>
3             <groupId>org.aspectj</groupId>
4             <artifactId>aspectjweaver</artifactId>
5             <version>1.8.5</version>
6         </dependency>


4.五、編寫鏈接數據庫的配置信息

  以前咱們在src/main/resources目錄下建立了一個config.properties文件,裏面的內容是空的,如今咱們就在這個config.properties文件中編寫鏈接數據庫須要使用到的相關信息,以下所示:


 1 #hibernate.dialect=org.hibernate.dialect.OracleDialect
 2 #driverClassName=oracle.jdbc.driver.OracleDriver
 3 #validationQuery=SELECT 1 FROM DUAL
 4 #jdbc_url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
 5 #jdbc_username=gacl
 6 #jdbc_password=xdp
 7 
 8 hibernate.dialect=org.hibernate.dialect.MySQLDialect
 9 driverClassName=com.mysql.jdbc.Driver
10 validationQuery=SELECT 1
11 jdbc_url=jdbc:mysql://localhost:3306/sshe?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
12 jdbc_username=root
13 jdbc_password=XDP
14 
15 #hibernate.dialect=org.hibernate.dialect.SQLServerDialect
16 #driverClassName=net.sourceforge.jtds.jdbc.Driver
17 #validationQuery=SELECT 1
18 #jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sshe
19 #jdbc_username=sa
20 #jdbc_password=123456
21 
22 #jndiName=java:comp/env/dataSourceName
23 
24 hibernate.hbm2ddl.auto=update
25 hibernate.show_sql=true
26 hibernate.format_sql=true


4.六、編寫Hibernate與Spring整合的配置文件

  在src/main/resources目錄下新建一個spring-hibernate.xml文件,以下圖所示:

  

  spring-hibernate.xml文件的內容以下:


  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
  3 http://www.springframework.org/schema/beans 
  4 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
  5 http://www.springframework.org/schema/tx 
  6 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  7 http://www.springframework.org/schema/aop 
  8 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  9 ">
 10 
 11     <!-- JNDI方式配置數據源 -->
 12     <!-- 
 13     <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
 14          <property name="jndiName" value="${jndiName}"></property> 
 15     </bean> 
 16     -->
 17 
 18     <!-- 配置數據源 -->
 19     <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
 20         <property name="url" value="${jdbc_url}" />
 21         <property name="username" value="${jdbc_username}" />
 22         <property name="password" value="${jdbc_password}" />
 23 
 24         <!-- 初始化鏈接大小 -->
 25         <property name="initialSize" value="0" />
 26         <!-- 鏈接池最大使用鏈接數量 -->
 27         <property name="maxActive" value="20" />
 28         <!-- 鏈接池最大空閒 -->
 29         <property name="maxIdle" value="20" />
 30         <!-- 鏈接池最小空閒 -->
 31         <property name="minIdle" value="0" />
 32         <!-- 獲取鏈接最大等待時間 -->
 33         <property name="maxWait" value="60000" />
 34 
 35         <!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->
 36 
 37         <property name="validationQuery" value="${validationQuery}" />
 38         <property name="testOnBorrow" value="false" />
 39         <property name="testOnReturn" value="false" />
 40         <property name="testWhileIdle" value="true" />
 41 
 42         <!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 -->
 43         <property name="timeBetweenEvictionRunsMillis" value="60000" />
 44         <!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 -->
 45         <property name="minEvictableIdleTimeMillis" value="25200000" />
 46 
 47         <!-- 打開removeAbandoned功能 -->
 48         <property name="removeAbandoned" value="true" />
 49         <!-- 1800秒,也就是30分鐘 -->
 50         <property name="removeAbandonedTimeout" value="1800" />
 51         <!-- 關閉abanded鏈接時輸出錯誤日誌 -->
 52         <property name="logAbandoned" value="true" />
 53 
 54         <!-- 監控數據庫 -->
 55         <!-- <property name="filters" value="stat" /> -->
 56         <property name="filters" value="mergeStat" />
 57     </bean>
 58 
 59     <!-- 配置hibernate session工廠 -->
 60     <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
 61         <property name="dataSource" ref="dataSource" />
 62         <property name="hibernateProperties">
 63             <props>
 64                 <!-- web項目啓動時是否更新表結構 -->
 65                 <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
 66                 <!-- 系統使用的數據庫方言,也就是使用的數據庫類型 -->
 67                 <prop key="hibernate.dialect">${hibernate.dialect}</prop>
 68                 <!-- 是否打印Hibernate生成的SQL到控制檯 -->
 69                 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
 70                 <!-- 是否格式化打印出來的SQL -->
 71                 <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
 72             </props>
 73         </property>
 74 
 75         <!-- 自動掃描註解方式配置的hibernate類文件 -->
 76         <property name="packagesToScan">
 77             <list>
 78                 <value>me.gacl.model</value>
 79             </list>
 80         </property>
 81 
 82         <!-- 自動掃描hbm方式配置的hibernate文件和.hbm文件 -->
 83         <!-- 
 84         <property name="mappingDirectoryLocations">
 85             <list>
 86                 <value>classpath:me/gacl/model/hbm</value>
 87             </list>
 88         </property>
 89          -->
 90     </bean>
 91 
 92     <!-- 配置事務管理器 -->
 93     <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
 94         <property name="sessionFactory" ref="sessionFactory"></property>
 95     </bean>
 96 
 97     <!-- 註解方式配置事物 -->
 98     <!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->
 99 
100     <!-- 攔截器方式配置事物 -->
101     <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
102         <tx:attributes>
103             <!-- 以以下關鍵字開頭的方法使用事物 -->
104             <tx:method name="add*" />
105             <tx:method name="save*" />
106             <tx:method name="update*" />
107             <tx:method name="modify*" />
108             <tx:method name="edit*" />
109             <tx:method name="delete*" />
110             <tx:method name="remove*" />
111             <tx:method name="repair" />
112             <tx:method name="deleteAndRepair" />
113             <!-- 以以下關鍵字開頭的方法不使用事物 -->
114             <tx:method name="get*" propagation="SUPPORTS" />
115             <tx:method name="find*" propagation="SUPPORTS" />
116             <tx:method name="load*" propagation="SUPPORTS" />
117             <tx:method name="search*" propagation="SUPPORTS" />
118             <tx:method name="datagrid*" propagation="SUPPORTS" />
119             <!-- 其餘方法不使用事物 -->
120             <tx:method name="*" propagation="SUPPORTS" />
121         </tx:attributes>
122     </tx:advice>
123     <!-- 切面,將事物用在哪些對象上 -->
124     <aop:config>
125         <aop:pointcut id="transactionPointcut" expression="execution(* me.gacl.service..*Impl.*(..))" />
126         <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
127     </aop:config>
128     
129 </beans>


4.七、編寫單元測試代碼

一、在MySQL中建立sshe數據庫

  SQL腳本:

CREATE DATABASE SSHE;

二、在src/main/java中建立me.gac.model包,在包中編寫一個 User類,以下圖所示:

  

代碼以下:

 1 package me.gacl.model;
 2 
 3 import java.util.Date;
 4 
 5 import javax.persistence.Column;
 6 import javax.persistence.Entity;
 7 import javax.persistence.Id;
 8 import javax.persistence.Table;
 9 import javax.persistence.Temporal;
10 import javax.persistence.TemporalType;
11 
12 @Entity
13 @Table(name = "T_USER", schema = "SSHE")
14 public class User implements java.io.Serializable {
15 
16     // Fields
17     private String id;
18     private String name;
19     private String pwd;
20     private Date createdatetime;
21     private Date modifydatetime;
22 
23     // Constructors
24 
25     /** default constructor */
26     public User() {
27     }
28 
29     /** minimal constructor */
30     public User(String id, String name, String pwd) {
31         this.id = id;
32         this.name = name;
33         this.pwd = pwd;
34     }
35 
36     /** full constructor */
37     public User(String id, String name, String pwd, Date createdatetime, Date modifydatetime) {
38         this.id = id;
39         this.name = name;
40         this.pwd = pwd;
41         this.createdatetime = createdatetime;
42         this.modifydatetime = modifydatetime;
43     }
44 
45     // Property accessors
46     @Id
47     @Column(name = "ID", unique = true, nullable = false, length = 36)
48     public String getId() {
49         return this.id;
50     }
51 
52     public void setId(String id) {
53         this.id = id;
54     }
55 
56     @Column(name = "NAME",nullable = false, length = 100)
57     public String getName() {
58         return this.name;
59     }
60 
61     public void setName(String name) {
62         this.name = name;
63     }
64 
65     @Column(name = "PWD", nullable = false, length = 32)
66     public String getPwd() {
67         return this.pwd;
68     }
69 
70     public void setPwd(String pwd) {
71         this.pwd = pwd;
72     }
73 
74     @Temporal(TemporalType.TIMESTAMP)
75     @Column(name = "CREATEDATETIME", length = 7)
76     public Date getCreatedatetime() {
77         return this.createdatetime;
78     }
79 
80     public void setCreatedatetime(Date createdatetime) {
81         this.createdatetime = createdatetime;
82     }
83 
84     @Temporal(TemporalType.TIMESTAMP)
85     @Column(name = "MODIFYDATETIME", length = 7)
86     public Date getModifydatetime() {
87         return this.modifydatetime;
88     }
89 
90     public void setModifydatetime(Date modifydatetime) {
91         this.modifydatetime = modifydatetime;
92     }
93 }


  三、在src/main/java中建立me.gacl.dao包,在包中編寫一個 UserDaoI接口,以下圖所示:

  

代碼以下:


 1 package me.gacl.dao;
 2 
 3 import java.io.Serializable;
 4 
 5 import me.gacl.model.User;
 6 
 7 public interface UserDaoI {
 8 
 9     /**
10      * 保存用戶
11      * @param user
12      * @return
13      */
14     Serializable save(User user); 
15 }


  在src/main/java中建立me.gacl.dao.impl包,在包中編寫 UserDaoImpl實現類,以下圖所示:

  

代碼以下:


 1 package me.gacl.dao.impl;
 2 
 3 import java.io.Serializable;
 4 
 5 import org.hibernate.SessionFactory;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.stereotype.Repository;
 8 
 9 import me.gacl.dao.UserDaoI;
10 import me.gacl.model.User;
11 
12 @Repository("userDao")
13 public class UserDaoImpl implements UserDaoI {
14     
15     /**
16      * 使用@Autowired註解將sessionFactory注入到UserDaoImpl中
17      */
18     @Autowired
19     private SessionFactory sessionFactory;
20     
21     @Override
22     public Serializable save(User user) {
23         return sessionFactory.getCurrentSession().save(user);
24     }
25 }


  這裏使用@Repository("userDao")註解完成dao注入, 使用@Autowired註解將sessionFactory注入到UserDaoImpl中。

  四、在以前建立好的UserServiceI接口中添加一個save方法的定義,以下:


 1 package me.gacl.service;
 2 
 3 import java.io.Serializable;
 4 import me.gacl.model.User;
 5 
 6 /**
 7  * 測試
 8  * @author gacl
 9  *
10  */
11 public interface UserServiceI {
12 
13     /**
14      * 測試方法
15      */
16     void test();
17     
18     /**
19      * 保存用戶
20      * @param user
21      * @return
22      */
23     Serializable save(User user); 
24 }


  五、在UserServiceImpl類中實現save方法,以下:


 1 package me.gacl.service.impl;
 2 
 3 import java.io.Serializable;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Service;
 7 
 8 import me.gacl.dao.UserDaoI;
 9 import me.gacl.model.User;
10 import me.gacl.service.UserServiceI;
11 //使用Spring提供的@Service註解將UserServiceImpl標註爲一個Service
12 @Service("userService")
13 public class UserServiceImpl implements UserServiceI {
14 
15     /**
16      * 注入userDao
17      */
18     @Autowired
19     private UserDaoI userDao;
20     
21     @Override
22     public void test() {
23         System.out.println("Hello World!");
24     }
25 
26     @Override
27     public Serializable save(User user) {
28         return userDao.save(user);
29     }
30 }


  六、在src/main/test下的me.gacl.test包中編寫 TestHibernate類,代碼以下:

 1 package me.gacl.test;
 2 
 3 import java.util.Date;
 4 import java.util.UUID;
 5 
 6 import me.gacl.model.User;
 7 import me.gacl.service.UserServiceI;
 8 
 9 import org.junit.Before;
10 import org.junit.Test;
11 import org.springframework.context.ApplicationContext;
12 import org.springframework.context.support.ClassPathXmlApplicationContext;
13 
14 public class TestHibernate {
15 
16     private UserServiceI userService;
17     
18     /**
19      * 這個before方法在全部的測試方法以前執行,而且只執行一次
20      * 全部作Junit單元測試時一些初始化工做能夠在這個方法裏面進行
21      * 好比在before方法裏面初始化ApplicationContext和userService
22      */
23     @Before
24     public void before(){
25         ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-hibernate.xml"});
26         userService = (UserServiceI) ac.getBean("userService");
27     }
28     
29     @Test
30     public void testSaveMethod(){
31         //ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-hibernate.xml"});
32         //UserServiceI userService = (UserServiceI) ac.getBean("userService");
33         User user = new User();
34         user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
35         user.setName("孤傲蒼狼");
36         user.setPwd("123");
37         user.setCreatedatetime(new Date()); 
38         userService.save(user);
39     }
40 }


  執行Junit單元測試,以下所示:
  

  測試經過,再看看sshe數據庫,以下圖所示:

  

  Hibernate在執行過程當中,先幫咱們在sshe數據庫中建立一張t_user表,t_user的表結構根據User實體類中的屬性定義來建立的,而後再將數據插入到t_user表中,以下圖所示:

  

  到此,Hibernate4開發環境的搭建而且與Spring整合的工做算是所有完成而且測試經過了。

5、三大框架綜合測試

  通過前面的四大步驟,咱們已經成功地搭建好基於struts2+hibernate4+spring3這三大框架的整合開發環境,下面咱們來綜合測試一下三大框架配合使用進行開發的效果。

5.一、完善web.xml文件中的配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 5     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 6     <display-name></display-name>
 7     <welcome-file-list>
 8         <welcome-file>index.jsp</welcome-file>
 9     </welcome-file-list>
10 
11     <!-- Spring監聽器 -->
12     <listener>
13         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
14     </listener>
15     <!-- Spring配置文件位置 -->
16     <context-param>
17         <param-name>contextConfigLocation</param-name>
18         <param-value>classpath:spring.xml,classpath:spring-hibernate.xml</param-value>
19     </context-param>
20     
21     <!-- 防止spring內存溢出監聽器 -->
22     <listener>
23         <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
24     </listener>
25     
26     <!-- openSessionInView配置 -->
27     <filter>
28         <filter-name>openSessionInViewFilter</filter-name>
29         <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
30         <init-param>
31             <param-name>singleSession</param-name>
32             <param-value>true</param-value>
33         </init-param>
34     </filter>
35     <filter-mapping>
36         <filter-name>openSessionInViewFilter</filter-name>
37         <url-pattern>*.action</url-pattern>
38     </filter-mapping>
39     
40     <!-- Struts2的核心過濾器配置 -->
41     <filter>
42         <filter-name>struts2</filter-name>
43         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
44     </filter>
45     <!-- Struts2過濾器攔截全部的.action請求 -->
46     <filter-mapping>
47         <filter-name>struts2</filter-name>
48         <url-pattern>*.action</url-pattern>
49     </filter-mapping>
50     
51     <!-- druid監控頁面,使用${pageContext.request.contextPath}/druid/index.html訪問 -->
52     <servlet>
53         <servlet-name>druidStatView</servlet-name>
54         <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
55     </servlet>
56     <servlet-mapping>
57         <servlet-name>druidStatView</servlet-name>
58         <url-pattern>/druid/*</url-pattern>
59     </servlet-mapping>
60 </web-app>


5.二、編寫測試代碼

  在TestAction類中添加一個saveUser方法,以下:


 1 package me.gacl.action;
 2 
 3 import java.util.Date;
 4 import java.util.UUID;
 5 
 6 import me.gacl.model.User;
 7 import me.gacl.service.UserServiceI;
 8 
 9 import org.apache.struts2.convention.annotation.Action;
10 import org.apache.struts2.convention.annotation.Namespace;
11 import org.apache.struts2.convention.annotation.ParentPackage;
12 import org.springframework.beans.factory.annotation.Autowired;
13 
14 @ParentPackage("basePackage")
15 @Action(value="strust2Test")//使用convention-plugin插件提供的@Action註解將一個普通java類標註爲一個能夠處理用戶請求的Action
16 @Namespace("/")//使用convention-plugin插件提供的@Namespace註解爲這個Action指定一個命名空間
17 public class TestAction {
18     
19     /**
20      * 注入userService
21      */
22     @Autowired
23     private UserServiceI userService;
24 
25     /**
26      * http://localhost:8080/SSHE/strust2Test!test.action
27      * MethodName: test
28      * Description: 
29      * @author xudp
30      */
31     public void test(){
32         System.out.println("進入TestAction");
33         userService.test();
34     }
35     
36     /**
37      * http://localhost:8080/SSHE/strust2Test!saveUser.action
38      */
39     public void saveUser(){
40         User user = new User();
41         user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
42         user.setName("xdp孤傲蒼狼");
43         user.setPwd("123456");
44         user.setCreatedatetime(new Date()); 
45         userService.save(user);
46     }
47 }


  執行【Maven install】操做,從新編譯和發佈項目,在執行【Maven install】操做以前,須要修改TestSpring這個測試類中的test方法的代碼,以下:


 1 package me.gacl.test;
 2 
 3 import me.gacl.service.UserServiceI;
 4 
 5 import org.junit.Test;
 6 import org.springframework.context.ApplicationContext;
 7 import org.springframework.context.support.ClassPathXmlApplicationContext;
 8 
 9 public class TestSpring {
10 
11     @Test
12     public void test(){
13         //經過spring.xml配置文件建立Spring的應用程序上下文環境
14         //ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring.xml");
15         /**
16          *由於已經整合了Hibernate,UserServiceImpl類中使用到了userDao,
17          *userDao是由spring建立而且注入給UserServiceImpl類的,而userDao中又使用到了sessionFactory對象
18          *而建立sessionFactory對象時須要使用到spring-hibernate.xml這個配置文件中的配置項信息,
19          *因此建立Spring的應用程序上下文環境時,須要同時使用spring.xml和spring-hibernate.xml這兩個配置文件
20          *不然在執行Maven install命令時,由於maven會先執行test方法中的代碼,而代碼執行到
21          *UserServiceI userService = (UserServiceI) ac.getBean("userService");
22          *這一行時就會由於userDao中使用到sessionFactory對象沒法正常建立的而出錯,這樣執行Maven install命令編譯項目時就會失敗!
23          *
24          */
25         ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-hibernate.xml"});
26         //從Spring的IOC容器中獲取bean對象
27         UserServiceI userService = (UserServiceI) ac.getBean("userService");
28         //執行測試方法
29         userService.test();
30     }
31 }

複製代碼

複製代碼

  每次執行【Maven install】命令時都會執行Junit單元測試中的代碼有時候感受挺累贅的,有時候每每就是由於一些單元測試中的代碼致使【Maven install】命令編譯項目失敗!

  將編譯好的項目部署到tomcat服務器中運行,輸入地址:http://localhost:8080/SSHE/strust2Test!saveUser.action進行訪問,以下所示:

  

  訪問action的過程當中沒有出現錯誤,而且後臺也沒有報錯而且打印出了Hibernate執行插入操做時的SQL語句,以下所示:

  

  這說明三大框架整合開發的測試經過了。以上就是使用使用Maven搭建Struts2+Spring3+Hibernate4的整合開發環境的所有內容。

相關文章
相關標籤/搜索