SpringMVC+Spring+Hibernate+EHCache

jopen 10年前

使用eclipse+maven构建SpringMVC+Spring+Hibernate+EHCache项目 摘要 使用eclipse+maven构建SpringMVC+Spring+Hibernate+EHCache项目

1、首先使用maven构建一个web项目,目录结构如下

SpringMVC+Spring+Hibernate+EHCache

 

2、配置pom.xml

  <!-- spring  -->       <dependency>           <groupId>org.springframework</groupId>           <artifactId>spring-context</artifactId>           <version>4.1.2.RELEASE</version>       </dependency>       <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-core</artifactId>     <version>4.1.2.RELEASE</version>    </dependency>       <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-beans</artifactId>     <version>4.1.2.RELEASE</version>    </dependency>       <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-web</artifactId>     <version>4.1.2.RELEASE</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-webmvc</artifactId>     <version>4.1.2.RELEASE</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-aop</artifactId>     <version>4.1.2.RELEASE</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-jdbc</artifactId>     <version>4.1.2.RELEASE</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-tx</artifactId>     <version>4.1.2.RELEASE</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-orm</artifactId>     <version>4.1.2.RELEASE</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-context-support</artifactId>     <version>4.1.2.RELEASE</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-expression</artifactId>     <version>4.1.2.RELEASE</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-aspects</artifactId>     <version>4.1.2.RELEASE</version>    </dependency>    <dependency>     <groupId>org.springframework</groupId>     <artifactId>spring-oxm</artifactId>     <version>4.1.2.RELEASE</version>    </dependency>        <dependency>     <groupId>org.aspectj</groupId>     <artifactId>aspectjweaver</artifactId>     <version>1.8.4</version>    </dependency>                <!-- hibernate  -->      <dependency>        <groupId>org.hibernate</groupId>        <artifactId>hibernate-core</artifactId>        <version>4.3.7.Final</version>      </dependency>     <!-- hibernate-ehcache 缓存 -->      <dependency>                      <groupId>org.hibernate</groupId>                      <artifactId>hibernate-ehcache</artifactId>                      <version>4.3.7.Final</version>                  </dependency>      <dependency>     <groupId>net.sf.ehcache</groupId>     <artifactId>ehcache-core</artifactId>     <version>2.6.9</version>    </dependency>                 <!-- alibaba druid -->      <dependency>                   <groupId>com.alibaba</groupId>                   <artifactId>druid</artifactId>                   <version>1.0.11</version>           </dependency>                        <!-- mysql -->    <dependency>     <groupId>mysql</groupId>     <artifactId>mysql-connector-java</artifactId>     <version>5.1.34</version>    </dependency>                        <!-- jackson -->           <dependency>     <groupId>com.fasterxml.jackson.core</groupId>     <artifactId>jackson-databind</artifactId>     <version>2.4.4</version>    </dependency>    <dependency>     <groupId>com.fasterxml.jackson.core</groupId>     <artifactId>jackson-core</artifactId>     <version>2.4.4</version>    </dependency>    <dependency>     <groupId>com.fasterxml.jackson.core</groupId>     <artifactId>jackson-annotations</artifactId>     <version>2.4.4</version>    </dependency>          <!-- jstl -->    <dependency>     <groupId>javax.servlet.jsp.jstl</groupId>     <artifactId>jstl-api</artifactId>     <version>1.2</version>    </dependency>    <dependency>                          <groupId>javax.servlet</groupId>                          <artifactId>javax.servlet-api</artifactId>                          <version>3.1.0</version>                  </dependency>                  <dependency>                          <groupId>javax.servlet.jsp</groupId>                          <artifactId>jsp-api</artifactId>                          <version>2.2</version>                  </dependency>                              <!-- jta  -->    <dependency>     <groupId>javax.transaction</groupId>     <artifactId>jta</artifactId>     <version>1.1</version>    </dependency>                 <!-- slf4j-log4j -->    <dependency>          <groupId>org.slf4j</groupId>          <artifactId>slf4j-api</artifactId>          <version>1.7.2</version>      </dependency>      <dependency>          <groupId>org.slf4j</groupId>          <artifactId>slf4j-log4j12</artifactId>          <version>1.7.2</version>      </dependency>      <dependency>          <groupId>log4j</groupId>          <artifactId>log4j</artifactId>          <version>1.2.17</version>      </dependency>               <!-- Apache commons -->    <dependency>     <groupId>commons-io</groupId>     <artifactId>commons-io</artifactId>     <version>2.4</version>    </dependency>        <dependency>     <groupId>commons-codec</groupId>     <artifactId>commons-codec</artifactId>     <version>1.10</version>    </dependency>        <dependency>     <groupId>org.apache.commons</groupId>     <artifactId>commons-lang3</artifactId>     <version>3.3.2</version>    </dependency>        <dependency>     <groupId>commons-beanutils</groupId>     <artifactId>commons-beanutils</artifactId>     <version>1.9.2</version>    </dependency>        <dependency>     <groupId>commons-fileupload</groupId>     <artifactId>commons-fileupload</artifactId>     <version>1.3.1</version>    </dependency>        <dependency>     <groupId>commons-collections</groupId>     <artifactId>commons-collections</artifactId>     <version>3.2.1</version>    </dependency>        <dependency>     <groupId>commons-httpclient</groupId>     <artifactId>commons-httpclient</artifactId>     <version>3.1</version>    </dependency>        <dependency>     <groupId>commons-cli</groupId>     <artifactId>commons-cli</artifactId>     <version>1.2</version>    </dependency>        <dependency>     <groupId>asm</groupId>     <artifactId>asm-commons</artifactId>     <version>3.3.1</version>    </dependency>       <!-- jaxen -->    <dependency>     <groupId>jaxen</groupId>     <artifactId>jaxen</artifactId>     <version>1.1.6</version>    </dependency>       <!-- ezmorph -->    <dependency>     <groupId>net.sf.ezmorph</groupId>     <artifactId>ezmorph</artifactId>     <version>1.0.6</version>    </dependency>       <!-- dom4j -->    <dependency>     <groupId>dom4j</groupId>     <artifactId>dom4j</artifactId>     <version>1.6.1</version>    </dependency>             

 

3、创建所需的配置文件

SpringMVC+Spring+Hibernate+EHCache

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"        updateCheck="false">        <!--            name:cache唯一标识             eternal:缓存是否永久有效             maxElementsInMemory:内存中最大缓存对象数            overflowToDisk(true,false):缓存对象达到最大数后,将缓存写到硬盘中            diskPersistent:硬盘持久化            timeToIdleSeconds:缓存清除时间             timeToLiveSeconds:缓存存活时间            memoryStoreEvictionPolicy:缓存清空策略            1.FIFO:first in first out 先讲先出            2.LFU: Less Frequently Used 一直以来最少被使用的            3.LRU:Least Recently Used  最近最少使用的         -->        <defaultCache maxElementsInMemory="1000" eternal="false"            timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" />                            <cache name="infoCache" eternal="false" maxElementsInMemory="1000"            overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="3600"            timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LFU" />    </ehcache>

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>  <!DOCTYPE hibernate-configuration PUBLIC          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">    <hibernate-configuration>      <session-factory>      </session-factory>  </hibernate-configuration>

log4j.properties

#此句为将等级为INFO的日志信息输出到stdout和logfile这两个目的地,stdout和logfile的定义在下面的代码,可以任#意起名。  #等级可分为OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL  #如果配置OFF则不打出任何信息,如果配置为INFO这样只显示INFO, WARN, ERROR的log信息,而DEBUG信息不会被显示,#具体讲解可参照第三部分定义配置文件中的logger。    log4j.rootLogger=INFO, stdout, logfile    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=%d{ABSOLUTE} %5p %c:%L - %m%n    log4j.appender.logfile=org.apache.log4j.RollingFileAppender  log4j.appender.logfile.File=log/info.log  log4j.appender.logfile.MaxFileSize=10240KB    log4j.logger.com.wong=DEBUG  log4j.logger.org.springframework=INFO  log4j.logger.org.hibernate=ERROR    log4j.appender.logfile.MaxBackupIndex=3    log4j.appender.logfile.layout=org.apache.log4j.PatternLayout  log4j.appender.logfile.layout.ConversionPattern=%d %p [%c %L] - %m%n

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:aop="http://www.springframework.org/schema/aop"         xmlns:tx="http://www.springframework.org/schema/tx"         xmlns:security="http://www.springframework.org/schema/security"         xmlns:context="http://www.springframework.org/schema/context"         xmlns:mvc="http://www.springframework.org/schema/mvc"         xsi:schemaLocation="http://www.springframework.org/schema/beans            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd            http://www.springframework.org/schema/tx            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd            http://www.springframework.org/schema/security            http://www.springframework.org/schema/security/spring-security.xsd            http://www.springframework.org/schema/context            http://www.springframework.org/schema/context/spring-context-3.0.xsd            http://www.springframework.org/schema/aop            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd            http://www.springframework.org/schema/mvc            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"         default-autowire="byName" default-lazy-init="false">      <!-- 注意上面的default-autowire="byName",如果没有这个声明那么HibernateDaoSupport中的sessionFactory不会被注入 -->        <!-- 定义受环境影响易变的变量 -->      <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">          <property name="locations">              <list>                  <value>classpath:/web.properties</value>              </list>          </property>      </bean>        <!-- 约定优于配置,约定优于配置 -->      <bean id="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="maxActive" value="200" />       <property name="initialSize" value="10" />       <property name="maxWait" value="60000" />       <property name="minIdle" value="10" />           <property name="timeBetweenEvictionRunsMillis" value="60000" />       <property name="minEvictableIdleTimeMillis" value="300000" />           <property name="filters" value="stat" />       <property name="validationQuery" value="SELECT 'x'" />       <property name="testWhileIdle" value="true" />       <property name="testOnBorrow" value="false" />       <property name="testOnReturn" value="false" />   </bean>        <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">          <property name="dataSource" ref="dataSource"/>            <property name="packagesToScan">              <list>                  <value>${hibernate.scanpackages}</value>              </list>          </property>                    <property name="hibernateProperties">           <value>                 hibernate.dialect=${hibernate.dialect}                 hibernate.connection.driver_class=${jdbc.driverclass}                 hibernate.connection.url=${jdbc.url}                 hibernate.connection.username=${jdbc.username}                 hibernate.connection.password=${jdbc.password}                 hibernate.hbm2ddl.auto=${hiberante.hbm2ddl}                 hibernate.show_sql=${hibernate.showsql}                 hibernate.format_sql=${hibernate.formatsql}                 hibernate.cache.use_second_level_cache=${hibernate.secondlevelcache}                 hibernate.cache.use_query_cache=${hibernate.querycache}                 hibernate.cache.region.factory_class=${hibernate.classcache}             </value>        </property>        </bean>        <!-- 事务配置 -->      <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">          <property name="sessionFactory" ref="sessionFactory"/>      </bean>            <tx:advice id="txadvice">          <tx:attributes>              <tx:method name="get*" read-only="true"/>              <tx:method name="query*" read-only="true"/>              <tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/>          </tx:attributes>      </tx:advice>        <aop:config>          <aop:advisor                  pointcut="execution(* com.wong.min.service.impl.*ServiceImpl.*(..))"                  advice-ref="txadvice"/>      </aop:config>            <!-- 扫描组件 -->      <context:component-scan base-package="com.wong"/>             <!-- 使用默认的Servlet来响应静态文件  -->      <mvc:default-servlet-handler/>            <!-- 开启AOP切面注解  -->      <aop:aspectj-autoproxy proxy-target-class="true"/>    </beans>

  web.properties

### jdbc ###  jdbc.driverclass=com.mysql.jdbc.Driver  jdbc.url=jdbc:mysql://localhost:3306/min?createDatabaseIfNotExist=true&amp;useUnicode=true&amp;characterEncoding=utf-8  jdbc.username=root  jdbc.password=root    ### hibernate ###  hibernate.dialect=org.hibernate.dialect.MySQLDialect  hibernate.showsql=true  hibernate.formatsql=true  hiberante.hbm2ddl=update  hibernate.scanpackages=com.wong.min.entity  hibernate.secondlevelcache=true  hibernate.querycache=true  hibernate.classcache=org.hibernate.cache.ehcache.EhCacheRegionFactory

    springMVC-servlet.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"         xmlns:mvc="http://www.springframework.org/schema/mvc"         xsi:schemaLocation="http://www.springframework.org/schema/beans             http://www.springframework.org/schema/beans/spring-beans-4.0.xsd             http://www.springframework.org/schema/context             http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"         default-autowire="byName">     <!-- 开启springmvc注解,定义只扫描@Cotroller  -->      <mvc:annotation-driven/>      <context:component-scan base-package="com.wong"  use-default-filters="false">       <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />      </context:component-scan>        <!-- 文件上传支持Bean -->      <bean id="multipartResolver"            class="org.springframework.web.multipart.commons.CommonsMultipartResolver">          <!--最大文件不能超过1GB-->          <property name="maxUploadSize" value="1073741824"/>      </bean>     <!-- 返回jsp view -->      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"            p:prefix="/WEB-INF/view/"            p:suffix=".jsp"/>                  <!-- 返回json数据 -->      <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">                <property name="messageConverters">                    <list >                        <ref bean="mappingJacksonHttpMessageConverter" />                    </list>                </property>            </bean>       <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">           <property name="supportedMediaTypes">               <list>                   <value>application/json;charset=UTF-8</value>              </list>           </property>     </bean>       <!-- 处理静态资源 -->   <mvc:resources location="/static/" mapping="/static/**"/>   <mvc:resources location="/post/" mapping="/post/**"/>  </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_2_5.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">          <display-name>Archetype Created Web Application</display-name>        <context-param>          <param-name>contextConfigLocation</param-name>          <param-value>              classpath:spring.xml          </param-value>      </context-param>        <!-- Character Encoding filter -->      <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>           <filter>          <filter-name>osivFilter</filter-name>          <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>      </filter>            <filter-mapping>          <filter-name>osivFilter</filter-name>          <url-pattern>*</url-pattern>      </filter-mapping>           <!--  <filter>          <filter-name>springSecurityFilterChain</filter-name>          <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>      </filter>            <filter-mapping>          <filter-name>springSecurityFilterChain</filter-name>          <url-pattern>/*</url-pattern>      </filter-mapping>   -->      <servlet>          <servlet-name>springMVC</servlet-name>          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>          <load-on-startup>2</load-on-startup>      </servlet>        <servlet-mapping>          <servlet-name>springMVC</servlet-name>          <url-pattern>/</url-pattern>      </servlet-mapping>        <listener>          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>      </listener>          <welcome-file-list>          <welcome-file>/index.jsp</welcome-file>      </welcome-file-list>  </web-app>