做了三年多的JavaEE開發了,在平時的JavaEE開發中,為了能夠用最快的速度開發項目,一般都會選擇使用Struts2,SpringMVC,Spring,Hibernate,MyBatis這些開源框架來開發項目,而這些框架一般不是單獨使用的,經常是Struts2+Spring3+Hibernate、SpringMVC+Spring+Hibernate、SpringMVC+Spring+Mybatis這幾種組合中的一種,也就是多個框架配合起來使用。今天來總結一下如何使用Maven搭建Struts2+Spring3+Hibernate4的整合開發環境。
一、建立Maven工程
第一步:
第二步:
第三步:
創建好的項目如下圖所示:
第四步:
注意:這里的JDK要選擇默認的,這樣別人在使用的時候,如何JDk不一致的話也不會出錯,如下圖所示:
第五步:
創建Maven標准目錄
src/main/java
src/main/resources
src/test/java
src/test/resources
第六步:
發布項目:Maven install
清除編譯過的項目:Maven clean
Maven install命令執行結果如下:
OK,Maven工程創建成功!
二、搭建Spring3開發環境
2.1、下載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.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.3、編寫單元測試
首先,在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.4、在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開發環境搭建成功!
三、搭建Struts2開發環境並整合Spring3
3.1、下載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.2、編寫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.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.4、編寫測試
首先,在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總是會遇到一些奇怪的問題,好在憑借着一些平時積累的解決問題的經驗把問題解決了。
四、搭建Hibernate4開發環境並整合Spring3
4.1、下載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.2、添加數據庫驅動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.3、添加數據庫連接池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.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.5、編寫連接數據庫的配置信息
之前我們在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.6、編寫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.7、編寫單元測試代碼
1、在MySQL中創建sshe數據庫
SQL腳本:
CREATE DATABASE SSHE;
2、在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 }
3、在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中。
4、在之前創建好的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 }
5、在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 }
6、在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整合的工作算是全部完成並且測試通過了。
五、三大框架綜合測試
經過前面的四大步驟,我們已經成功地搭建好基於struts2+hibernate4+spring3這三大框架的整合開發環境,下面我們來綜合測試一下三大框架配合使用進行開發的效果。
5.1、完善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.2、編寫測試代碼
在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的整合開發環境的全部內容。