Maven 工程整合 Spring mvc + Mybatis +Velocity

1. 創建 maven web 工程,添加依賴

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.test</groupId>
	<artifactId>spring.mybatis</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	
	<!-- 定義常量 -->
	<properties>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

		<!-- 第三方庫 -->
		<junit.version>4.11</junit.version>
		<spring.version>4.1.6.RELEASE</spring.version>
		<org.mybatis.version>3.2.7</org.mybatis.version>
		<org.mybatis.spring.version>1.2.0</org.mybatis.spring.version>
		<mysql.connector.java.version>5.1.26</mysql.connector.java.version>
		<druid.version>1.0.7</druid.version>
		<ehcache.version>2.8.3</ehcache.version>
		<org.slf4j.log4j12.version>1.7.5</org.slf4j.log4j12.version>
		<fastjson.version>1.2.5</fastjson.version>
		<jackson.version>2.6.1</jackson.version>
		<jackson-mapper-asl.version>1.9.13</jackson-mapper-asl.version>
		<aspectjweaver.version>1.8.1</aspectjweaver.version>
		<javax.servlet.version>3.0.1</javax.servlet.version>
		<commons-lang3.version>3.1</commons-lang3.version>
		<commons-fileupload.version>1.2.2</commons-fileupload.version>
		<commons-io.version>2.4</commons-io.version>
		<velocity.version>1.7</velocity.version>
		<velocity-tools.version>1.3</velocity-tools.version>
		<cglib-nodep.version>3.1</cglib-nodep.version>
		<commons-digester.version>2.0</commons-digester.version>
	</properties>

	<!-- 配置maven下載jar的中央倉庫,默認的是國外的 -->
	<repositories>
		<repository>
			<id>oschinaRepository</id>
			<name>local private nexus</name>
			<url>http://maven.oschina.net/content/groups/public/</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>
	</repositories>

	<dependencyManagement>
		<dependencies>
			<!-- 設置所有傳遞依賴的spring框架使用定義的版本,Maven 2.0.9+ -->
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-framework-bom</artifactId>
				<version>${spring.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<dependencies>

		<!-- 單元測試框架 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
		</dependency>

		<!-- servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${javax.servlet.version}</version>
			<scope>provided</scope>
		</dependency>

		<!-- cglib -->
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib-nodep</artifactId>
			<version>${cglib-nodep.version}</version>
		</dependency>

		<!-- Spring 框架 -->
		<!-- 加入spring mvc依賴包 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
		</dependency>
		<!-- 加入spring測試依賴包 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<scope>test</scope>
		</dependency>

		<!-- velocity -->
		<dependency>
			<groupId>org.apache.velocity</groupId>
			<artifactId>velocity</artifactId>
			<version>${velocity.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.velocity</groupId>
			<artifactId>velocity-tools</artifactId>
			<version>${velocity-tools.version}</version>
			<!-- 去除 velocity 中不需要的依賴 -->
			<exclusions>
				<exclusion>
					<groupId>javax.servlet</groupId>
					<artifactId>servlet-api</artifactId>
				</exclusion>
				<exclusion>
					<groupId>velocity</groupId>
					<artifactId>velocity</artifactId>
				</exclusion>
				<exclusion>
					<groupId>commons-beanutils</groupId>
					<artifactId>commons-beanutils</artifactId>
				</exclusion>
				<exclusion>
					<groupId>commons-digester</groupId>
					<artifactId>commons-digester</artifactId>
				</exclusion>
				<exclusion>
					<groupId>commons-collections</groupId>
					<artifactId>commons-collections</artifactId>
				</exclusion>
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
				<exclusion>
					<groupId>commons-validator</groupId>
					<artifactId>commons-validator</artifactId>
				</exclusion>
				<exclusion>
					<groupId>sslext</groupId>
					<artifactId>sslext</artifactId>
				</exclusion>
				<exclusion>
					<groupId>struts</groupId>
					<artifactId>struts</artifactId>
				</exclusion>
				<exclusion>
					<groupId>oro</groupId>
					<artifactId>oro</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>commons-digester</groupId>
			<artifactId>commons-digester</artifactId>
			<version>${commons-digester.version}</version>
		</dependency>

		<!-- Mybatis框架 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${org.mybatis.version}</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>${org.mybatis.spring.version}</version>
		</dependency>

		<!-- 數據庫驅動 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.connector.java.version}</version>
		</dependency>

		<!-- 加入druid數據源依賴包 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>${druid.version}</version>
		</dependency>

		<!-- ehcache需要的依賴 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
		</dependency>
		<!-- 加入ehcache -->
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
			<version>${ehcache.version}</version>
		</dependency>

		<!-- Log 框架 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j.log4j12.version}</version>
		</dependency>

		<!-- 加入fastjson依賴包 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>${fastjson.version}</version>
		</dependency>

		<!--jackson -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>${jackson-mapper-asl.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${jackson.version}</version>
		</dependency>

		<!-- aspectj -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>${aspectjweaver.version}</version>
		</dependency>

		<!-- commons -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>${commons-lang3.version}</version>
		</dependency>

		<!-- 文件上傳所需要的依賴 -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>${commons-fileupload.version}</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>${commons-io.version}</version>
		</dependency>

	</dependencies>
	<build>
		<finalName>spring.mybatis</finalName>
		<plugins>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.19</version>
				<configuration>
					<skip>true</skip>
					<testFailureIgnore>true</testFailureIgnore>
					<includes>
						<include>**/*Test.java</include>
						<include>**/*TestCase.java</include>
						<include>**/Test*.java</include>
					</includes>
					<excludes>
						<exclude>**/Abstract*.java</exclude>
					</excludes>
 				</configuration>
			</plugin>

			<plugin>
				<!-- 編譯的時候使用JDK8和UTF8編碼 -->
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
 					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>

			<!-- war打包插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.2</version>
				<configuration>
					<!-- http://maven.apache.org/plugins/maven-war-plugin/ -->
					<packagingExcludes>WEB-INF/web.xml</packagingExcludes>
				</configuration>
			</plugin>

		</plugins>
	</build>
</project>
2. 將 maven web 工程設置成 servlet 3.0 項目

    詳見:http://blog.csdn.net/u011310774/article/details/48338225

3. 添加 spring 配置文件

--> spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- 引入項目配置文件 -->
	<!-- <context:property-placeholder location="classpath:config.properties" /> -->
	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:config.properties</value>
			</list>
		</property>
	</bean>

	<!-- 自動掃描dao和service包(自動注入) -->
	<context:component-scan
		base-package="com.danguiedu.wantuo.dao,com.danguiedu.wantuo.service" />
	<!-- 默認的註解映射的支持 -->
	<context:annotation-config />
	
	<!-- 導入其它 spring 配置文件 -->
	<import resource="spring-mybatis.xml" />
	<import resource="spring-ehcache.xml" />
	
</beans>
--> spring-mybatis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:c="http://www.springframework.org/schema/c" xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
		http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
	
	<!-- JNDI方式配置數據源 -->
	<!-- 
	<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> 
		<property name="jndiName" value="${jndiName}"></property>
	</bean> 
	-->

	<!-- 配置druid數據源 -->
	<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<!-- 數據庫連接基礎信息 -->
		<property name="url" value="${jdbc_url}" />
		<property name="username" value="${jdbc_username}" />
		<property name="password" value="${jdbc_password}" />

		<!-- 初始化連接大小 -->
		<property name="initialSize" value="0" />
		<!-- 連接池最大使用連接數量 -->
		<property name="maxActive" value="1500" />
		<!-- 連接池最小空閒 -->
		<property name="minIdle" value="0" />
		<!-- 獲取連接最大等待時間 -->
		<property name="maxWait" value="60000" />

		<!-- 是否緩存preparedStatement,也就是PSCache。並且指定每個連接上PSCache的大小。PSCache對支持遊標的數據庫性能提升巨大,比如說oracle。在mysql下建議關閉。默認false --> 
		<!-- property name="poolPreparedStatements" value="true" />
			<property name="maxPoolPreparedStatementPerConnectionSize" value="33" />
		-->

		<!-- 驗證數據庫連接有效性,要求是一個查詢語句 -->
		<property name="validationQuery" value="${validationQuery}" />

		<!-- 建議配置爲true,不影響性能,並且保證安全性。申請連接的時候檢測,如果空閒時間大於timeBetweenEvictionRunsMillis,執行validationQuery檢測連接是否有效。 -->
		<property name="testWhileIdle" value="true" />
		<!-- 申請連接時執行validationQuery檢測連接是否有效,配置爲true會降低性能 -->
		<property name="testOnBorrow" value="false" />
		<!-- 歸還連接時執行validationQuery檢測連接是否有效,配置爲true會降低性能 -->
		<property name="testOnReturn" value="false" />

		<!-- 有兩個含義:1) Destroy線程會檢測連接的間隔時間,如果連接空閒時間大於等於minEvictableIdleTimeMillis則關閉物理連接 2) testWhileIdle的判斷依據,詳細看testWhileIdle屬性的說明 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />
		<!-- 配置一個連接在池中最小生存的時間(連接保持空閒而不被驅逐的最長時間),單位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="25200000" />

		<!-- 對於長時間不使用的連接強制關閉 -->
		<property name="removeAbandoned" value="true" />
		<!-- 超過30分鐘開始關閉空閒連接,1800秒,也就是30分鐘 -->
		<property name="removeAbandonedTimeout" value="1800" />
		<!-- 關閉abanded連接時輸出錯誤日誌 -->
		<property name="logAbandoned" value="true" />

		<!-- 監控數據庫 -->
		<!-- <property name="filters" value="mergeStat" /> -->
		<property name="filters" value="stat" />
	</bean>

	<!-- mybatis 的 SqlSession 的工廠: SqlSessionFactoryBean -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- <property name="typeAliasesPackage" value="com.domain" /> -->
		<property name="mapperLocations"
			value="classpath:com/danguiedu/wantuo/mapper/*/*Mapper.xml" />
	</bean>

	<!-- 配置掃描器 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 掃描dao這個包以及它的子包下的所有映射接口類 -->
		<property name="basePackage" value="com.danguiedu.wantuo.dao" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	</bean>

	<!-- 配置事務管理器 DataSourceTransactionManager -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!-- 註解方式配置事物 -->
	<!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->

	<!-- 攔截器方式配置事物 -->
	<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="append*" propagation="REQUIRED" />
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="do*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="modify*" propagation="REQUIRED" />
			<tx:method name="edit*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="remove*" propagation="REQUIRED" />
			<tx:method name="init" propagation="REQUIRED" />
			<tx:method name="delAndInit" propagation="REQUIRED" />

			<tx:method name="get*" propagation="REQUIRED" read-only="true" />
			<tx:method name="find*" propagation="REQUIRED" read-only="true" />
			<tx:method name="load*" propagation="REQUIRED" read-only="true" />
			<tx:method name="search*" propagation="REQUIRED" read-only="true" />
			<tx:method name="datagrid*" propagation="REQUIRED"
				read-only="true" />

			<tx:method name="*" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>
	<aop:config>
		<aop:pointcut id="transactionPointcut"
			expression="execution(* com.danguiedu.wantuo.service..*Impl.*(..))" />
		<aop:advisor pointcut-ref="transactionPointcut"
			advice-ref="transactionAdvice" />
	</aop:config>
	
	<import resource="spring-druid.xml" />

</beans>
--> spring-druid.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:c="http://www.springframework.org/schema/c" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
		http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

	<!-- 配置druid監控spring jdbc -->
	<bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor" />

	<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
		<property name="patterns">
			<list>
				<value>com.danguiedu.wantuo.service.*</value>
			</list>
		</property>
	</bean>
	<aop:config>
		<aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
	</aop:config>

</beans>
--> spring-ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:c="http://www.springframework.org/schema/c" xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
		http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

	<!-- 開啓spring緩存 -->
	<cache:annotation-driven cache-manager="cacheManager" />
	<bean id="cacheManagerFactory"
		class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
		p:configLocation="classpath:ehcache.xml" p:shared="false" />
	<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
		p:cacheManager-ref="cacheManagerFactory" />

</beans>
4. 添加 spring-mvc.xml 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:c="http://www.springframework.org/schema/c" xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
		http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

	<!-- 自動掃描controller包下的所有類,使其認爲spring mvc的控制器 -->
	<context:component-scan base-package="com.danguiedu.wantuo.controller" />

	<!--避免IE出現下載JSON文件的情況 -->
	<mvc:annotation-driven>
		<mvc:message-converters register-defaults="true">
			<bean
				class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
				<property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>

	<!-- velocity 模板信息設置 -->
	<bean id="velocityConfigurer"
		class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
		<!-- 設置模板文件位置 -->
		<property name="resourceLoaderPath" value="WEB-INF/views/" />
		<property name="velocityProperties">
			<props>
				<prop key="directive.foreach.counter.name">loopCounter</prop>
				<prop key="directive.foreach.counter.initial.value">0</prop>
				<prop key="input.encoding">UTF-8</prop><!-- 指定模板引擎進行模板處理的編碼 -->
				<prop key="output.encoding">UTF-8</prop><!-- 指定輸出流的編碼 -->
			</props>
		</property>
	</bean>

	<!-- 設置視圖解析工具 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
		<!-- 設置視圖文件後綴名 -->
		<property name="suffix" value=".html" />
		<!-- velocity toolbox 設置 -->
		<property name="toolboxConfigLocation" value="/WEB-INF/classes/vm-toolbox.xml" />
		<!-- 避免亂碼 -->
		<property name="contentType" value="text/html;charset=UTF-8" />
		<property name="dateToolAttribute" value="dateTool" />
		<property name="numberToolAttribute" value="numberTool" />
		<property name="exposeRequestAttributes" value="true" />
		<property name="exposeSessionAttributes" value="true" />
	</bean>

	<!-- SpringMVC上傳文件時,需要配置MultipartResolver處理器 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 指定所上傳文件的總大小不能超過5MB。注意maxUploadSize屬性的限制不是針對單個文件,而是所有文件的容量之和 -->
		<!-- <property name="maxUploadSize" value="5000000"/> -->
	</bean>

	<!-- 處理靜態資源請求 -->
	<!-- <mvc:resources mapping="/assets/**" location="/assets/*" /> -->

</beans>
5. 配置 web.xml
<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

	<display-name>spring.mybaitis</display-name>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

	<!-- 加載配置文件 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:spring.xml</param-value>
	</context-param>
	
	<!-- spring -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>

	<!-- spring mvc -->
	<servlet>
		<servlet-name>springMvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
		<async-supported>true</async-supported>
	</servlet>
	<servlet-mapping>
		<servlet-name>springMvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<!-- druid 監控 -->
	<filter>
		<filter-name>druidWebStatFilter</filter-name>
		<filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
		<init-param>
			<param-name>exclusions</param-name>
			<param-value>/themes/*,*.css,*.js,*.gif,*.jpg,*.png,*.ico,*.eot,*.svg,*.ttf,*.woff,*.jsp,*.tpl,/druid/*</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>druidWebStatFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<servlet>
		<servlet-name>druidStatView</servlet-name>
		<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>druidStatView</servlet-name>
		<url-pattern>/druid/*</url-pattern>
	</servlet-mapping>

	<!-- log4j -->
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.properties</param-value>
	</context-param>
	<context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>spring-mybatis.root </param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>

	<!-- 設置請求編碼格式 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- 靜態資源 -->
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.css</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.js</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.json</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.gif</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.tpl</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.png</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.jpg</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.ico</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.doc</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.xls</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.docx</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.xlsx</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.txt</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.swf</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.eot</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.svg</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.ttf</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.woff</url-pattern>
	</servlet-mapping>
	<!-- 
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.html</url-pattern>
	</servlet-mapping> 
	-->

</web-app>
6. 其它相關配置文件
-->config.properties
jdbc_url=jdbc:mysql://127.0.0.1:3306/dgedu?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=root
jdbc_password=123
driver_name=com.mysql.jdbc.Driver

validationQuery=SELECT 1
-->ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" monitoring="autodetect" dynamicConfig="true">

	<diskStore path="java.io.tmpdir" />
	<!-- <diskStore path="D:/cache" />   -->
	
	<!-- 默認配置 -->
	<!-- <defaultCache overflowToDisk="true" eternal="false"/>  --> 
	<defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />
	
	<!--  
    name:Cache的唯一標識
    maxElementsInMemory:內存中最大緩存對象數
    maxElementsOnDisk:磁盤中最大緩存對象數,若是0表示無窮大
    eternal:Element是否永久有效,一但設置了,timeout將不起作用
    overflowToDisk:配置此屬性,當內存中Element數量達到maxElementsInMemory時,Ehcache將會Element寫到磁盤中 
    timeToIdleSeconds:設置Element在失效前的允許閒置時間。僅當element不是永久有效時使用,可選屬性,默認值是0,也就是可閒置時間無窮大 
    timeToLiveSeconds:設置Element在失效前允許存活時間。最大時間介於創建時間和失效時間之間。僅當element不是永久有效時使用,默認是0.,也就是element存活時間無窮大  
    diskPersistent:是否緩存虛擬機重啓期數據  
    diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒 
    diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每個Cache都應該有自己的一個緩衝區 
    memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你可以設置爲FIFO(先進先出)或是LFU(較少使用)  
    -->

	<!-- 用戶註冊個數緩存 -->
	<cache name="registerCountCache" maxElementsInMemory="10000" maxElementsOnDisk="1000" eternal="false" overflowToDisk="true" diskSpoolBufferSizeMB="20" timeToIdleSeconds="600" timeToLiveSeconds="1200" memoryStoreEvictionPolicy="LFU" />
	
	<!-- 微信公衆賬號token有效期2小時 -->
	<cache name="weixinTokenCache" maxElementsInMemory="10000" maxElementsOnDisk="1000" eternal="false" overflowToDisk="true" diskSpoolBufferSizeMB="20" timeToIdleSeconds="7000" timeToLiveSeconds="7000" memoryStoreEvictionPolicy="LFU" />
	
</ehcache>
-->log4j.properties
 ### 設置###
log4j.rootLogger = debug,stdout,D,E


### 輸出信息到控制擡 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n


### 輸出DEBUG 級別以上的日誌到=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n


### 輸出ERROR 級別以上的日誌到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n 
-->vm-toolbox.xml
<?xml version="1.0" encoding="UTF-8" ?>
<toolbox>
    <xhtml>true</xhtml>
    <tool>
        <key>stringUtils</key>
        <scope>application</scope>
        <class>org.apache.commons.lang.StringUtils</class>
    </tool>
</toolbox>

7. 創建表

CREATE TABLE `wt_banner` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `banner_name` varchar(20) DEFAULT '' COMMENT '導航欄名稱',
  `create_date` int(11) unsigned DEFAULT '0' COMMENT '年月日',
  `create_time` int(11) unsigned DEFAULT '0' COMMENT '時分秒',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

8. 使用 mybatis-generator 工具生成實體類和映射文件,再將文件拷貝到對應目錄下
    詳見:http://blog.csdn.net/u011310774/article/details/48269031

9. 使用 Junit 進行單元測試

package com.danguiedu.wantuo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.danguiedu.wantuo.dao.website.BannerMapper;
import com.danguiedu.wantuo.model.website.Banner;

@RunWith(SpringJUnit4ClassRunner.class) //使用 Spring test 框架
@ContextConfiguration(locations = { "classpath:spring.xml" }) //加載配置
public class SpringJunitBaseTest {
	
	@Autowired
	private BannerMapper bannerMapper;
	
	@Test
	public void test() {
		Banner banner = new Banner("首頁",20150910,171230);
		bannerMapper.insert(banner);
	}

}

10. 創建 service 實現類

package com.danguiedu.wantuo.service.website;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.danguiedu.wantuo.dao.website.BannerMapper;
import com.danguiedu.wantuo.model.website.Banner;

@Service
public class BannerServiceImpl implements IBannerService {
	@Autowired
	private BannerMapper bannerMapper;
	
	public Banner getBannerById(int id){
		Banner banner = bannerMapper.selectByPrimaryKey(id);
		return banner;
	}
}

11. 創建 controller

package com.danguiedu.wantuo.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.danguiedu.wantuo.model.website.Banner;
import com.danguiedu.wantuo.service.website.IBannerService;

@Controller
public class TestController {
	@Autowired
	private IBannerService bannerServiceImpl;
	
	@RequestMapping("/nihao")
	public String m(HttpServletRequest request) {
		Banner banner = bannerServiceImpl.getBannerById(1);
		request.setAttribute("velocity", banner);
		return "index";
	}
}

12. 右鍵工程 -> Run As -> Maven Install 編譯打包

13. tomcat 下運行訪問

附件:源碼  http://download.csdn.net/download/u011310774/9210613
注:源碼 web.xml 文件忘了配置 druid 的監控,可以從以上的 web.xml 配置中找到

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章