1. 程式人生 > >Maven搭建SpringMvc+Spring+Hibernate框架

Maven搭建SpringMvc+Spring+Hibernate框架

假設你已經在Myeclipse上面建立好啦一個Maven專案,現在我們開始往pom.xml裡面新增jar的配置。

<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>yfkj.gz</groupId>
	<artifactId>task</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>	
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<spring.version>4.3.5.RELEASE</spring.version>
		<hibernate.version>5.2.5.Final</hibernate.version>
		<jackson.version>2.8.5</jackson.version>
		<junit.version>4.12</junit.version>
		<ehcache.version>2.10.3</ehcache.version>
		<log4j.version>1.2.17</log4j.version>
		<mysql.version>5.1.37</mysql.version>
		<druid.version>1.0.27</druid.version>
		<aspectjweaver.version>1.8.10</aspectjweaver.version>
		<webVersion>3.0</webVersion>
	</properties>
	<dependencies>
		<!-- junit 單元測試 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<!-- spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
			<scope>test</scope>
		</dependency>

		<!-- 使用SpringMVC需配置 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- 關係型資料庫整合時需配置 如hibernate jpa等 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-ehcache</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		
		
		<!-- 二級快取ehcache -->  
        <dependency>  
            <groupId>net.sf.ehcache</groupId>  
            <artifactId>ehcache</artifactId>  
            <version>${ehcache.version}</version>  
        </dependency>
        
        <!-- log4j -->  
        <dependency>  
            <groupId>log4j</groupId>  
            <artifactId>log4j</artifactId>  
            <version>${log4j.version}</version>  
        </dependency>  
  
        <!-- mysql連線 -->  
        <dependency>  
            <groupId>mysql</groupId>  
            <artifactId>mysql-connector-java</artifactId>  
            <version>${mysql.version}</version>  
        </dependency>
        
        <!-- 阿里巴巴資料來源 -->
		<dependency>
		    <groupId>com.alibaba</groupId>
		    <artifactId>druid</artifactId>
		    <version>${druid.version}</version>
		</dependency>
		
		<dependency>  
            <groupId>com.fasterxml.jackson.core</groupId>  
            <artifactId>jackson-annotations</artifactId>  
            <version>${jackson.version}</version>  
        </dependency>  
  
        <dependency>  
            <groupId>com.fasterxml.jackson.core</groupId>  
            <artifactId>jackson-core</artifactId>  
            <version>${jackson.version}</version>  
        </dependency>  
  
        <dependency>  
            <groupId>com.fasterxml.jackson.core</groupId>  
            <artifactId>jackson-databind</artifactId>  
            <version>${jackson.version}</version>  
        </dependency>  
  
        <!-- aop -->  
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>${aspectjweaver.version}</version>
        </dependency>
        
        <!-- servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>3.0-alpha-1</version>
            <scope>provided</scope>
        </dependency>
  
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>
我們來看看專案的結構圖:

下面開始各種框架的配置檔案

資料庫config.properties的配置:

url.driver=com.mysql.jdbc.Driver
url.jdbc=jdbc:mysql://192.168.1.150:3306/wms?useUnicode=true&characterEncoding=UTF-8
url.name=****
url.pass=****

#hibernate config
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = update
hibernate.cache.use_second_level_cache = true
hibernate.cache.use_query_cache = true
hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.EhCacheRegionFactory
hibernate.cache.provider_configuration_file_resource_path =ehcache.xml
快取配置檔案ehcache.xml:
<?xml version="1.0" encoding="UTF-8"?>  
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">  
    <diskStore path="java.io.tmpdir/ehcache" />  
    <!-- DefaultCache setting. -->  
     <defaultCache  
            maxElementsInMemory="1000"  
            eternal="false"  
            timeToIdleSeconds="120"  
            timeToLiveSeconds="120"  
            maxElementsOnDisk="1000000"  
            overflowToDisk="true"   
            memoryStoreEvictionPolicy="LRU">  
              
    </defaultCache> 
  
  
</ehcache> 
spring配置檔案:
<?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:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
            http://www.springframework.org/schema/beans/spring-beans-4.3.xsd  
            http://www.springframework.org/schema/context  
            http://www.springframework.org/schema/context/spring-context-4.3.xsd">  
    <!-- 載入配置檔案 -->  
      
    <context:property-placeholder location="classpath:config.properties"/>  
    <!-- 掃描service自動注入為bean -->  
    <context:component-scan base-package="yfkj.gz.task.service.impl,yfkj.gz.task.dao.impl" />  
  
</beans>
spring-hibernate.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:tx="http://www.springframework.org/schema/tx"  
    xmlns:aop="http://www.springframework.org/schema/aop"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd   
        http://www.springframework.org/schema/tx   
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd  
        http://www.springframework.org/schema/aop   
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">  
  
    <!-- 配置資料來源 Druid --> 
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<!-- MySQL資料庫配置 -->
		<property name="url"
			value="${url.jdbc}" />
		<property name="username" value="${url.name}" />
		<property name="password" value="${url.pass}" />
		<!-- SQL Server資料庫配置 -->
		<!-- <property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=yfkj" 
			/> <property name="username" value="sa" /> <property name="password" value="123456" 
			/> -->
		<!-- Oracle資料庫配置 -->
		<!-- <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:yfkj" 
			/> <property name="username" value="SYSTEM" /> <property name="password" 
			value="SkyNet888999" /> -->
		<!-- 配置初始化大小、最小、最大 -->
		<property name="initialSize" value="1" />
		<property name="minIdle" value="1" />
		<property name="maxActive" value="20" />
		<!-- 配置獲取連線等待超時的時間 -->
		<property name="maxWait" value="60000" />
		<!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />
		<!-- 配置一個連線在池中最小生存的時間,單位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="300000" />
		<!-- 開啟PSCache,並且指定每個連線上PSCache的大小 -->
		<property name="poolPreparedStatements" value="true" />
		<property name="maxPoolPreparedStatementPerConnectionSize"
			value="20" />
		<!-- 配置監控統計攔截的filters -->
		<property name="filters" value="stat,log4j,wall" />
	</bean>
  
    <!-- 配置hibernate的SessionFactory -->  
    <bean id="sessionFactory"  
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">  
        <!-- 注入資料來源 相關資訊看原始碼 -->  
        <property name="dataSource" ref="dataSource" />  
        <!-- hibernate配置資訊 -->  
        <property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>  
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>  
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>  
  
                <!-- 開啟二級快取 ehcache -->  
                <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>  
                <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>  
                <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>  
                <prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path}  
                </prop>  
            </props>  
        </property>  
        <!-- 掃描hibernate註解配置的entity -->  
        <property name="packagesToScan" value="yfkj.gz.task.entity" />  
    </bean>  
  
    <!-- 配置事務管理器 -->  
    <bean id="transactionManager"  
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">  
        <property name="sessionFactory" ref="sessionFactory" />  
    </bean>  
  
    <!-- 配置事務增強處理Bean,指定事務管理器 -->  
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">  
        <!-- 配置詳細事務處理語義 -->  
        <tx:attributes>  
            <tx:method name="insert*" propagation="REQUIRED" />  
            <tx:method name="update*" propagation="REQUIRED" />  
            <tx:method name="delete*" propagation="REQUIRED" />  
  
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />  
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />  
            <tx:method name="select*" propagation="SUPPORTS" read-only="true" />  
            <tx:method name="load*" propagation="SUPPORTS" read-only="true" />  
  
            <!-- 其他採用預設事務方式 -->  
            <tx:method name="*" />  
  
        </tx:attributes>  
    </tx:advice>  
  
    <!-- Spring aop事務管理 -->  
    <aop:config>  
        <!-- 配置切入點 -->  
        <aop:pointcut id="transactionPointcut"  
            expression="execution(* yfkj.gz.task.service..*impl.*(..))" />  
        <!-- 指定在txAdvice切入點應用txAdvice事務增強處理 -->  
        <aop:advisor pointcut-ref="transactionPointcut"  
            advice-ref="transactionAdvice" />  
    </aop:config>
    
    
    <!-- 使用annotation定義事務:如果沒有用到註解事物~可以關閉 -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> 
  
</beans> 
spring-mvc.xml配置檔案:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 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-4.3.xsd   
            http://www.springframework.org/schema/context   
            http://www.springframework.org/schema/context/spring-context-4.3.xsd   
            http://www.springframework.org/schema/mvc   
            http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

	<!-- 自動掃描@Controller注入為bean -->
	<context:component-scan base-package="yfkj.gz.task.controller" />

	<!-- 以下為SpringMVC配置 -->
	<mvc:annotation-driven>
		<!-- 返回json資料,@response使用 -->
		<mvc:message-converters register-defaults="true">
			<bean
				class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
				<property name="supportedMediaTypes">
					<list>
						<value>text/html;charset=UTF-8</value>
						<value>application/json;charset=UTF-8</value>
					</list>
				</property>

			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>

	<!-- 對模型檢視名稱的解析,即在模型檢視名稱新增前後綴 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/pages/" />
		<property name="suffix" value=".jsp" />
	</bean>

</beans>  
最後是我們的web.xml配置檔案:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<!-- 載入配置檔案 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring.xml,classpath:spring-hibernate.xml</param-value>
	</context-param>
	<!-- 中文過濾器 -->
	<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>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- openSessionInView配置 作用是延遲session關閉到view層 -->
	<filter>
		<filter-name>openSessionInViewFilter</filter-name>
		<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
		<init-param>
			<param-name>singleSession</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<!-- 監聽servletContext,啟動contextConfigLocation中的spring配置資訊 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 防止spring記憶體溢位監聽器 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>

	<servlet>
		<description>spring mvc servlet</description>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<!-- 此處配置的是SpringMVC的配置檔案 -->
			<param-value>classpath:spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>

	<filter-mapping>
		<filter-name>openSessionInViewFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>


	<!-- druid資料來源攔截配置,如果不需要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>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
		</init-param>
		<init-param>
			<param-name>profileEnable</param-name>
			<param-value>true</param-value>
		</init-param>
		<init-param>
			<param-name>sessionStatEnable</param-name>
			<param-value>true</param-value>
		</init-param>
		<init-param>
			<param-name>principalSessionName</param-name>
			<param-value>SESSION_SYS_USER</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>
		<init-param>
			<param-name>resetEnable</param-name>
			<param-value>true</param-value>
		</init-param>
		<init-param>
			<param-name>loginUsername</param-name>
			<param-value>gzyfkjDruid</param-value>
		</init-param>
		<init-param>
			<param-name>loginPassword</param-name>
			<param-value>[email protected]$$$</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>DruidStatView</servlet-name>
		<url-pattern>/druid/*</url-pattern>
	</servlet-mapping>

	<!-- 配置session超時時間,單位分鐘 -->
	<session-config>
		<session-timeout>30</session-timeout>
	</session-config>

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

</web-app>

原始碼地址:https://git.oschina.net/gzsjd/task