萬盛學電腦網

 萬盛學電腦網 >> Linux教程 >> Spring + Spring MVC + Mybatis 高性能web構建實例教程詳解

Spring + Spring MVC + Mybatis 高性能web構建實例教程詳解

   用最合適的技術去實現,並不斷追求最佳實踐。這就是架構之道。

  希望這篇文章能給你們帶來一些幫助,同時希望你們可以為這個項目貢獻你的想法。

  源碼地址:https://github.com/Eliteams/quick4j 點擊打開

  源碼地址:https://github.com/Eliteams/quick4j 點擊打開

  源碼地址:https://github.com/Eliteams/quick4j 點擊打開

  看我們的項目結構:

Spring + Spring MVC + Mybatis 高性能web構建實例教程詳解 linux

  是一個典型的Maven 項目 :

  src/main/Java:存放java源文件

  src/main/resources:存放程序資源、配置文件

  src/test/java:存放測試代碼文件

  src/main/webapp:web根目錄

  pom.xml : maven項目配置文件,管理依賴,編譯,打包

  主要的後端架構:spring + Spring MVC + Mybatis + Apache Shiro

  前端界面主要使用MetroNic 模板,

  先看我們搭建完成,跑起來的效果,這樣你才有興趣看下去:

  你可以 在github 上 checkout quick4j項目 查看 ,並跟下面步驟 來搭建:

  強烈建議你,checkout https://github.com/Eliteams/quick4j ,在本地跑起來,再試著自己搭建框架

  1、首先創建 maven 項目 ,用 idea 、eclipse 或 mvn 命令行都行

  2、配置 pom.xml ,添加框架依賴

<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.eliteams</groupId> 
  <artifactId>quick4j</artifactId> 
  <packaging>war</packaging> 
  <version>1.0.0</version> 
  <name>quick4j App</name> 
  <url>https://github.com/starzou/quick4j</url> 
  <build> 
    <finalName>quick4j</finalName> 
    <plugins> 
      <!-- Mybatis generator代碼生成插件 配置 --> 
      <plugin> 
        <groupId>org.mybatis.generator</groupId> 
        <artifactId>mybatis-generator-maven-plugin</artifactId> 
        <version>${plugin.mybatis.generator}</version> 
        <configuration> 
          <configurationFile>${mybatis.generator.generatorConfig.xml}</configurationFile> 
          <overwrite>true</overwrite> 
          <verbose>true</verbose> 
        </configuration> 
      </plugin> 
      <!--Maven編譯插件 配置--> 
      <plugin> 
        <groupId>org.apache.maven.plugins</groupId> 
        <artifactId>maven-compiler-plugin</artifactId> 
        <version>${plugin.maven-compiler}</version> 
        <configuration> 
          <source>${project.build.jdk}</source> 
          <target>${project.build.jdk}</target> 
          <encoding>${project.build.sourceEncoding}</encoding> 
        </configuration> 
      </plugin> 
    </plugins> 
    <!--配置Maven 對resource文件 過濾 --> 
    <resources> 
      <resource> 
        <directory>src/main/resources</directory> 
        <includes> 
          <include>**/*.properties</include> 
          <include>**/*.xml</include> 
        </includes> 
        <filtering>true</filtering> 
      </resource> 
      <resource> 
        <directory>src/main/java</directory> 
        <includes> 
          <include>**/*.properties</include> 
          <include>**/*.xml</include> 
        </includes> 
        <filtering>true</filtering> 
      </resource> 
    </resources> 
  </build> 
  <properties> 
    <!-- base setting --> 
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
    <project.build.locales>zh_CN</project.build.locales> 
    <project.build.jdk>1.7</project.build.jdk> 
    <!-- plugin setting --> 
    <mybatis.generator.generatorConfig.xml>${basedir}/src/test/resources/generatorConfig.xml</mybatis.generator.generatorConfig.xml> 
    <mybatis.generator.generatorConfig.properties>file:///${basedir}/src/test/resources/generatorConfig.properties</mybatis.generator.generatorConfig.properties> 
    <!-- plugin versions --> 
    <plugin.mybatis.generator>1.3.1</plugin.mybatis.generator> 
    <plugin.maven-compiler>3.1</plugin.maven-compiler> 
    <!-- lib versions --> 
    <junit.version>4.11</junit.version> 
    <spring.version>4.0.2.RELEASE</spring.version> 
    <mybatis.version>3.2.2</mybatis.version> 
    <mybatis.spring.version>1.2.2</mybatis.spring.version> 
    <mysql.connector.version>5.1.30</mysql.connector.version> 
    <postgresql.version>9.1-901.jdbc4</postgresql.version> 
    <slf4j.version>1.6.6</slf4j.version> 
    <log4j.version>1.2.12</log4j.version> 
    <httpclient.version>4.1.2</httpclient.version> 
    <jackson.version>1.9.13</jackson.version> 
    <c3p0.version>0.9.1.2</c3p0.version> 
    <druid.version>1.0.5</druid.version> 
    <tomcat.jdbc.version>7.0.53</tomcat.jdbc.version> 
    <jstl.version>1.2</jstl.version> 
    <google.collections.version>1.0</google.collections.version> 
    <cglib.version>3.1</cglib.version> 
    <shiro.version>1.2.3</shiro.version> 
    <commons.fileupload.version>1.3.1</commons.fileupload.version> 
    <commons.codec.version>1.9</commons.codec.version> 
    <commons.net.version>3.3</commons.net.version> 
    <aspectj.version>1.6.12</aspectj.version> 
    <netty.version>4.0.18.Final</netty.version> 
    <hibernate.validator.version>5.1.1.Final</hibernate.validator.version> 
  </properties> 
  <dependencies> 
    <!-- junit --> 
    <dependency> 
      <groupId>junit</groupId> 
      <artifactId>junit</artifactId> 
      <version>${junit.version}</version> 
    </dependency> 
    <!-- springframe start --> 
    <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-core</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-oxm</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-jdbc</artifactId> 
      <version>${spring.version}</version> 
    </dependency> 
    <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-webmvc</artifactId> 
      <version>${spring.version}</version> 
    </dependency> 
    <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-aop</artifactId> 
      <version>${spring.version}</version> 
    </dependency> 
    <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-context-support</artifactId> 
      <version>${spring.version}</version> 
    </dependency> 
    <dependency> 
      <groupId>org.springframework</groupId> 
      <artifactId>spring-test</artifactId> 
      <version>${spring.version}</version> 
    </dependency> 
    <!-- springframe end --> 
    <!-- mybatis start--> 
    <dependency> 
      <groupId>org.mybatis</groupId> 
      <artifactId>mybatis</artifactId> 
      <version>${mybatis.version}</version> 
    </dependency> 
    <dependency> 
      <groupId>org.mybatis</groupId> 
      <artifactId>mybatis-spring</artifactId> 
      <version>${mybatis.spring.version}</version> 
    </dependency> 
    <!--mybatis end--> 
    <!-- mysql-connector --> 
    <dependency> 
      <groupId>mysql</groupId> 
      <artifactId>mysql-connector-java</artifactId> 
      <version>${mysql.connector.version}</version> 
    </dependency> 
    <!-- DruidDataSource --> 
    <dependency> 
      <groupId>com.alibaba</groupId> 
      <artifactId>druid</artifactId> 
      <version>${druid.version}</version> 
    </dependency> 
    <!-- jackson --> 
    <dependency> 
      <groupId>org.codehaus.jackson</groupId> 
      <artifactId>jackson-mapper-asl</artifactId> 
      <version>${jackson.version}</version> 
    </dependency> 
    <!-- log start --> 
    <dependency> 
      <groupId>log4j</groupId> 
      <artifactId>log4j</artifactId> 
      <version>${log4j.version}</version> 
    </dependency> 
    <dependency> 
      <groupId>org.slf4j</groupId> 
      <artifactId>slf4j-api</artifactId> 
      <version>${slf4j.version}</version> 
    </dependency> 
    <dependency> 
      <groupId>org.slf4j</groupId> 
      <artifactId>slf4j-log4j12</artifactId> 
      <version>${slf4j.version}</version> 
    </dependency> 
    <!-- log end --> 
    <!-- servlet api --> 
    <dependency> 
      <groupId>javax.servlet</groupId> 
      <artifactId>javax.servlet-api</artifactId> 
      <version>3.0.1</version> 
      <scope>provided</scope> 
    </dependency> 
    <!-- jstl --> 
    <dependency> 
      <groupId>javax.servlet</groupId> 
      <artifactId>jstl</artifactId> 
      <version>${jstl.version}</version> 
    </dependency> 
    <!-- start apache --> 
    <dependency> 
      <groupId>commons-fileupload</groupId> 
      <artifactId>commons-fileupload</artifactId> 
      <version>${commons.fileupload.version}</version> 
    </dependency> 
    <dependency> 
      <groupId>org.apache.httpcomponents</groupId> 
      <artifactId>httpclient</artifactId> 
      <version>${httpclient.version}</version> 
    </dependency> 
    <dependency> 
      <groupId>commons-codec</groupId> 
      <artifactId>commons-codec</artifactId> 
      <version>${commons.codec.version}</version> 
    </dependency> 
    <dependency> 
      <groupId>commons-net</groupId> 
      <artifactId>commons-net</artifactId> 
      <version>${commons.net.version}</version> 
    </dependency> 
    <dependency> 
      <groupId>commons-logging</groupId> 
      <artifactId>commons-logging</artifactId> 
      <version>1.1.3</version> 
    </dependency> 
    <dependency> 
      <groupId>commons-collections</groupId> 
      <artifactId>commons-collections</artifactId> 
      <version>3.2.1</version> 
    </dependency> 
    <!-- end apache --> 
    <!-- google --> 
    <dependency> 
      <groupId>com.google.collections</groupId> 
      <artifactId>google-collections</artifactId> 
      <version>${google.collections.version}</version> 
    </dependency> 
    <!-- cglib --> 
    <dependency> 
      <groupId>cglib</groupId> 
      <artifactId>cglib-nodep</artifactId> 
      <version>${cglib.version}</version> 
    </dependency> 
    <!-- shiro --> 
    <dependency> 
      <groupId>org.apache.shiro</groupId> 
      <artifactId>shiro-spring</artifactId> 
      <version>${shiro.version}</version> 
    </dependency> 
    <dependency> 
      <groupId>org.apache.shiro</groupId> 
      <artifactId>shiro-ehcache</artifactId> 
      <version>${shiro.version}</version> 
    </dependency> 
    <dependency> 
      <groupId>org.apache.shiro</groupId> 
      <artifactId>shiro-core</artifactId> 
      <version>${shiro.version}</version> 
    </dependency> 
    <dependency> 
      <groupId>org.apache.shiro</groupId> 
      <artifactId>shiro-web</artifactId> 
      <version>${shiro.version}</version> 
    </dependency> 
    <dependency> 
      <groupId>org.apache.shiro</groupId> 
      <artifactId>shiro-quartz</artifactId> 
      <version>${shiro.version}</version> 
    </dependency> 
    <!-- aspectjweaver --> 
    <dependency> 
      <groupId>org.aspectj</groupId> 
      <artifactId>aspectjweaver</artifactId> 
      <version>${aspectj.version}</version> 
    </dependency> 
    <dependency> 
      <groupId>org.aspectj</groupId> 
      <artifactId>aspectjrt</artifactId> 
      <version>${aspectj.version}</version> 
    </dependency> 
    <!-- hibernate-validator --> 
    <dependency> 
      <groupId>org.hibernate</groupId> 
      <artifactId>hibernate-validator</artifactId> 
      <version>${hibernate.validator.version}</version> 
    </dependency> 
    <!-- netty --> 
    <dependency> 
      <groupId>io.netty</groupId> 
      <artifactId>netty-all</artifactId> 
      <version>${netty.version}</version> 
    </dependency> 
    <dependency> 
      <groupId>org.mybatis.generator</groupId> 
      <artifactId>mybatis-generator-core</artifactId> 
      <version>1.3.2</version> 
      <type>jar</type> 
      <scope>test</scope> 
    </dependency> 
  </dependencies> 
</project> 

3、配置web.xml

web.xml是一個項目的核心,看看它的一些配置:

配置 ContextLoaderListener 監聽器

配置Spring字符編碼過濾器

配置shiro 安全過濾器

配置Spring MVC 核心控制器 DispatcherServlet

配置一些頁面

spring 和 apache shiro 是由一個 ContextLoaderListener 監聽器 加載的配置文件,並初始化

<?xml version="1.0" encoding="utf-8"?> 
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> 
  <!-- Spring --> 
  <!-- 配置Spring配置文件路徑 --> 
  <context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value> 
      classpath*:applicationContext.xml 
      classpath*:applicationContext-shiro.xml 
    </param-value> 
  </context-param> 
  <!-- 配置Spring上下文監聽器 --> 
  <listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
  </listener> 
  <!-- Spring --> 
  <!-- 配置Spring字符編碼過濾器 --> 
  <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> 
  <!-- shiro 安全過濾器 --> 
  <filter> 
    <filter-name>shiroFilter</filter-name> 
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
    <async-supported>true</async-supported> 
    <init-param> 
      <param-name>targetFilterLifecycle</param-name> 
      <param-value>true</param-value> 
    </init-param> 
  </filter> 
  <filter-mapping> 
    <filter-name>shiroFilter</filter-name> 
    <url-pattern>/*</url-pattern> 
  </filter-mapping> 
  <!-- 配置log4j配置文件路徑 --> 
  <context-param> 
    <param-name>log4jConfigLocation</param-name> 
    <param-value>classpath:log4j.properties</param-value> 
  </context-param> 
  <!-- 60s 檢測日志配置 文件變化 --> 
  <context-param> 
    <param-name>log4jRefreshInterval</param-name> 
    <param-value>60000</param-value> 
  </context-param> 
  <!-- 配置Log4j監聽器 --> 
  <listener> 
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> 
  </listener> 
  <!-- Spring MVC 核心控制器 DispatcherServlet 配置 --> 
  <servlet> 
    <servlet-name>dispatcher</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> 
  </servlet> 
  <servlet-mapping> 
    <servlet-name>dispatcher</servlet-name> 
    <!-- 攔截所有/rest/* 的請求,交給DispatcherServlet處理,性能最好 --> 
    <url-pattern>/rest/*</url-pattern> 
  </servlet-mapping> 
  <!-- 首頁 --> 
  <welcome-file-list> 
    <welcome-file>rest/index</welcome-file> 
  </welcome-file-list> 
  <!-- 錯誤頁 --> 
  <error-page> 
    <error-code>404</error-code> 
    <location>/rest/page/404</location> 
  </error-page> 
  <error-page> 
    <error-code>500</error-code> 
    <location>/rest/page/500</location> 
  </error-page> 
  <error-page> 
    <exception-type>org.apache.shiro.authz.AuthorizationException</exception-type> 
    <location>/rest/page/401</location> 
  </error-page> 
</web-app> 

4、spring配置:

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 
    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:p="http://www.springframework.org/schema/p" 
    xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc" 
    xmlns:cache="http://www.springframework.org/schema/cache" 
    xsi:schemaLocation=" 
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context.xsd 
  http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans.xsd 
  http://www.springframework.org/schema/tx 
  http://www.springframework.org/schema/tx/spring-tx.xsd 
  http://www.springframework.org/schema/jdbc 
  http://www.springframework.org/schema/jdbc/spring-jdbc.xsd 
  http://www.springframework.org/schema/cache 
  http://www.springframework.org/schema/cache/spring-cache.xsd 
  http://www.springframework.org/schema/aop 
  http://www.springframework.org/schema/aop/spring-aop.xsd 
  http://www.springframework.org/schema/util 
  http://www.springframework.org/schema/util/spring-util.xsd"> 
  <!-- 自動掃描quick4j包 ,將帶有注解的類 納入spring容器管理 --> 
  <context:component-scan base-package="com.eliteams.quick4j"></context:component-scan> 
  <!-- 引入配置文件 --> 
  <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="locations"> 
      <list> 
        <value>classpath*:application.properties</value> 
      </list> 
    </property> 
  </bean> 
  <!-- dataSource 配置 --> 
  <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> 
    <!-- 基本屬性 url、user、password --> 
    <property name="url" value="${jdbc.url}"/> 
    <property name="username" value="${jdbc.username}"/> 
    <property name="password" value="${jdbc.password}"/> 
    <!-- 配置初始化大小、最小、最大 --> 
    <property name="initialSize" value="${ds.initialSize}"/> 
    <property name="minIdle" value="${ds.minIdle}"/> 
    <property name="maxActive" value="${ds.maxActive}"/> 
    <!-- 配置獲取連接等待超時的時間 --> 
    <property name="maxWait" value="${ds.maxWait}"/> 
    <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連接,單位是毫秒 --> 
    <property name="timeBetweenEvictionRunsMillis" value="${ds.timeBetweenEvictionRunsMillis}"/> 
    <!-- 配置一個連接在池中最小生存的時間,單位是毫秒 --> 
    <property name="minEvictableIdleTimeMillis" value="${ds.minEvictableIdleTimeMillis}"/> 
    <property name="validationQuery" value="SELECT 'x'"/> 
    <property name="testWhileIdle" value="true"/> 
    <property name="testOnBorrow" value="false"/> 
    <property name="testOnReturn" value="false"/> 
    <!-- 打開PSCache,並且指定每個連接上PSCache的大小 --> 
    <property name="poolPreparedStatements" value="false"/> 
    <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/> 
    <!-- 配置監控統計攔截的filters --> 
    <property name="filters" value="stat"/> 
  </bean> 
  <!-- mybatis文件配置,掃描所有mapper文件 --> 
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource" 
     p:configLocation="classpath:mybatis-config.xml" 
     p:mapperLocations="classpath:com/eliteams/quick4j/web/dao/*.xml"/> 
  <!-- spring與mybatis整合配置,掃描所有dao --> 
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="com.eliteams.quick4j.web.dao" 
     p:sqlSessionFactoryBeanName="sqlSessionFactory"/> 
  <!-- 對dataSource 數據源進行事務管理 --> 
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" 
     p:dataSource-ref="dataSource"/> 
  <!-- 事務管理 通知 --> 
  <tx:advice id="txAdvice" transaction-manager="transactionManager"> 
    <tx:attributes> 
      <!-- 對insert,update,delete 開頭的方法進行事務管理,只要有異常就回滾 --> 
      <tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/> 
      <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/> 
      <tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/> 
      <!-- select,count開頭的方法,開啟只讀,提高數據庫訪問性能 --> 
      <tx:method name="select*" read-only="true"/> 
      <tx:method name="count*" read-only="true"/> 
      <!-- 對其他方法 使用默認的事務管理 --> 
      <tx:method name="*"/> 
    </tx:attributes> 
  </tx:advice> 
  <!-- 事務 aop 配置 --> 
  <aop:config> 
    <aop:pointcut id="serviceMethods" expression="execution(* com.eliteams.quick4j.web.service..*(..))"/> 
    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/> 
  </aop:config> 
  <!-- 配置使Spring采用CGLIB代理 --> 
  <aop:aspectj-autoproxy proxy-target-class="true"/> 
  <!-- 啟用對事務注解的支持 --> 
  <tx:annotation-driven transaction-manager="transactionManager"/> 
  <!-- Cache配置 --> 
  <cache:annotation-driven cache-manager="cacheManager"/> 
  <bean id="ehCacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" 
     p:configLocation="classpath:ehcache.xml"/> 
  <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" 
     p:cacheManager-ref="ehCacheManagerFactory"/> 
</beans> 

application.properties

##JDBC Global Setting 
jdbc.driver=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql://localhost:3306/quick4j?useUnicode=true&characterEncoding=utf-8 
jdbc.username=root 
jdbc.password=admin123 
##DataSource Global Setting 
#配置初始化大小、最小、最大 
ds.initialSize=1 
ds.minIdle=1 
ds.maxActive=20 
#配置獲取連接等待超時的時間  
ds.maxWait=60000 
#配置間隔多久才進行一次檢測,檢測需要關閉的空閒連接,單位是毫秒 
ds.timeBetweenEvictionRunsMillis=60000 
#配置一個連接在池中最小生存的時間,單位是毫秒 
ds.minEvictableIdleTimeMillis=300000 

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?> 
<ehcache updateCheck="false" name="txswx-ehcache"> 
  <diskStore path="java.io.tmpdir"/> 
  <!-- DefaultCache setting. --> 
  <defaultCache maxEntriesLocalHeap="10000" eternal="true" timeToIdleSeconds="300" timeToLiveSeconds="600" 
         overflowToDisk="true" maxEntriesLocalDisk="100000"/> 
</ehcache> 

5、Apache Shiro 配置 : 要配置realms bean

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation=" 
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> 
  <description>apache shiro配置</description> 
  <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> 
    <property name="securityManager" ref="securityManager"/> 
    <property name="loginUrl" value="/rest/page/login"/> 
    <property name="successUrl" value="/rest/index"/> 
    <property name="unauthorizedUrl" value="/rest/page/401"/> 
    <property name="filterChainDefinitions"> 
      <value> 
        <!-- 靜態資源允許訪問 --> 
        /app/** = anon 
        /assets/** = anon 
        <!-- 登錄頁允許訪問 --> 
        /rest/user/login = anon 
        <!-- 其他資源需要認證 --> 
        /** = authc 
      </value> 
    </property> 
  </bean> 
  <!-- 緩存管理器 使用Ehcache實現 --> 
  <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> 
    <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/> 
  </bean> 
  <!-- 會話DAO --> 
  <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO"/> 
  <!-- 會話管理器 --> 
  <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> 
    <property name="sessionDAO" ref="sessionDAO"/> 
  </bean> 
  <!-- 安全管理器 --> 
  <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> 
    <property name="realms"> 
      <list> 
        <ref bean="securityRealm"/> 
      </list> 
    </property> 
    <!-- cacheManager,集合spring緩存工廠 --> 
    <!-- <property name="cacheManager" ref="shiroEhcacheManager" /> --> 
    <!-- <property name="sessionManager" ref="sessionManager" /> --> 
  </bean> 
  <!-- Shiro生命周期處理器 --> 
  <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> 
</beans> 

ehcache-shiro.xml

<ehcache updateCheck="false" name="shiroCache"> 
  <defaultCache 
      maxElementsInMemory="10000" 
      eternal="false" 
      timeToIdleSeconds="120" 
      timeToLiveSeconds="120" 
      overflowToDisk="false" 
      diskPersistent="false" 
      diskExpiryThreadIntervalSeconds="120" 
      /> 
</ehcache> 

6、MyBatis 配置

<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE configuration 
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
    "http://mybatis.org/dtd/mybatis-3-config.dtd"> 
<configuration> 
  <properties> 
    <property name="dialectClass" value="com.eliteams.quick4j.core.feature.orm.dialect.MySql5Dialect"/> 
  </properties> 
  <!-- 配置mybatis的緩存,延遲加載等等一系列屬性 --> 
  <settings> 
    <!-- 全局映射器啟用緩存 --> 
    <setting name="cacheEnabled" value="true"/> 
    <!-- 查詢時,關閉關聯對象即時加載以提高性能 --> 
    <setting name="lazyLoadingEnabled" value="true"/> 
    <!-- 對於未知的SQL查詢,允許返回不同的結果集以達到通用的效果 --> 
    <setting name="multipleResultSetsEnabled" value="true"/> 
    <!-- 允許使用列標簽代替列名 --> 
    <setting name="useColumnLabel" value="true"/> 
    <!-- 不允許使用自定義的主鍵值(比如由程序生成的UUID 32位編碼作為鍵值),數據表的PK生成策略將被覆蓋 --> 
    <setting name="useGeneratedKeys" value="false"/> 
    <!-- 給予被嵌套的resultMap以字段-屬性的映射支持 FULL,PARTIAL --> 
    <setting name="autoMappingBehavior" value="PARTIAL"/> 
    <!-- 對於批量更新操作緩存SQL以提高性能 BATCH,SIMPLE --> 
    <!-- <setting name="defaultExecutorType" value="BATCH" /> --> 
    <!-- 數據庫超過25000秒仍未響應則超時 --> 
    <!-- <setting name="defaultStatementTimeout" value="25000" /> --> 
    <!-- Allows using RowBounds on nested statements --> 
    <setting name="safeRowBoundsEnabled" value="false"/> 
    <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn. --> 
    <setting name="mapUnderscoreToCamelCase" value="true"/> 
    <!-- MyBatis uses local cache to prevent circular references and speed up repeated nested queries. By default (SESSION) all queries executed during a session are cached. If localCacheScope=STATEMENT  
      local session will be used just for statement execution, no data will be shared between two different calls to the same SqlSession. --> 
    <setting name="localCacheScope" value="SESSION"/> 
    <!-- Specifies the JDBC type for null values when no specific JDBC type was provided for the parameter. Some drivers require specifying the column JDBC type but others work with generic values  
      like NULL, VARCHAR or OTHER. --> 
    <setting name="jdbcTypeForNull" value="OTHER"/> 
    <!-- Specifies which Object's methods trigger a lazy load --> 
    <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/> 
    <!-- 設置關聯對象加載的形態,此處為按需加載字段(加載字段由SQL指 定),不會加載關聯表的所有字段,以提高性能 --> 
    <setting name="aggressiveLazyLoading" value="false"/> 
  </settings> 
  <typeAliases> 
    <package name="com.eliteams.quick4j.web.model"/> 
    <package name="com.eliteams.quick4j.web.enums"/> 
  </typeAliases> 
  <plugins> 
    <plugin interceptor="com.eliteams.quick4j.core.feature.orm.mybatis.PaginationResultSetHandlerInterceptor"/> 
    <plugin interceptor="com.eliteams.quick4j.core.feature.orm.mybatis.PaginationStatementHandlerInterceptor"/> 
  </plugins> 
</configuration> 

7、Spring MVC 配置

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p" 
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 
    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  
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd  
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> 
  <!-- 掃描controller(controller層注入) --> 
  <context:component-scan base-package="com.eliteams.quick4j.web.controller"/> 
  <!-- 會自動注冊DefaultAnnotationHandlerMapping與AnnotationMethodHandlerAdapter 兩個bean,是spring MVC為@Controllers分發請求所必須的 --> 
  <!-- 指定自己定義的validator --> 
  <mvc:annotation-driven validator="validator"/> 
  <!-- 以下 validator ConversionService 在使用 mvc:annotation-driven 會 自動注冊 --> 
  <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> 
    <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> 
    <!-- 如果不加默認到 使用classpath下的 ValidationMessages.properties --> 
    <property name="validationMessageSource" ref="messageSource"/> 
  </bean> 
  <!-- 國際化的消息資源文件(本系統中主要用於顯示/錯誤消息定制) --> 
  <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> 
    <property name="basenames"> 
      <list> 
        <!-- 在web環境中一定要定位到classpath 否則默認到當前web應用下找 --> 
        <value>classpath:messages</value> 
        <value>classpath:org/hibernate/validator/ValidationMessages</value> 
      </list> 
    </property> 
    <property name="useCodeAsDefaultMessage" value="false"/> 
    <property name="defaultEncoding" value="UTF-8"/> 
    <property name="cacheSeconds" value="60"/> 
  </bean> 
  <mvc:interceptors> 
    <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/> 
  </mvc:interceptors> 
  <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"> 
    <property name="defaultLocale" value="zh_CN"/> 
  </bean> 
  <!-- 支持返回json(避免IE在ajax請求時,返回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.MappingJacksonHttpMessageConverter"> 
    <property name="supportedMediaTypes"> 
      <list> 
        <value>text/plain;charset=UTF-8</value> 
        <value>application/json;charset=UTF-8</value> 
      </list> 
    </property> 
  </bean> 
  <!-- 支持返回json --> 
  <!-- 對模型視圖添加前後綴 --> 
  <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
     p:prefix="/WEB-INF/views/" p:suffix=".jsp"/> 
  <!-- 配置springMVC處理上傳文件的信息 --> 
  <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
    <property name="defaultEncoding" value="utf-8"/> 
    <property name="maxUploadSize" value="10485760000"/> 
    <property name="maxInMemorySize" value="40960"/> 
  </bean> 
  <!-- 啟用shrio授權注解攔截方式 --> 
  <aop:config proxy-target-class="true"></aop:config> 
  <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> 
    <property name="securityManager" ref="securityManager"/> 
  </bean> 
</beans> 

messages.properties : hibernate-validator 配置文件,國際化資源文件

#user 
user.username.null=用戶名不能為空 
user.password.null=密碼不能為空 
log4j.properties : 
[plain] view plain copy print?在CODE上查看代碼片派生到我的代碼片
# DEBUG,INFO,WARN,ERROR,FATAL 
LOG_LEVEL=INFO 
log4j.rootLogger=${LOG_LEVEL},CONSOLE,FILE 
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender 
log4j.appender.CONSOLE.Encoding=utf-8 
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout 
#log4j.appender.CONSOLE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss} %C{8}@(%F:%L):%m%n  
log4j.appender.CONSOLE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss} %C{1}@(%F:%L):%m%n 
log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender 
log4j.appender.FILE.File=${catalina.base}/logs/quick4j.log 
log4j.appender.FILE.Encoding=utf-8 
log4j.appender.FILE.DatePattern='.'yyyy-MM-dd 
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout 
#log4j.appender.FILE.layout=org.apache.log4j.HTMLLayout 
log4j.appender.FILE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH\:mm\:ss} %C{8}@(%F\:%L)\:%m%n 

quick4j.sql

/* 
SQLyog 企業版 - MySQL GUI v8.14  
MySQL - 5.5.27 : Database - quick4j 
********************************************************************* 
*/ 
/*!40101 SET NAMES utf8 */; 
/*!40101 SET SQL_MODE=''*/; 
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; 
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; 
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; 
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; 
CREATE DATABASE /*!32312 IF NOT EXISTS*/`quick4j` /*!40100 DEFAULT CHARACTER SET utf8 */; 
USE `quick4j`; 
/*Table structure for table `permission` */ 
DROP TABLE IF EXISTS `permission`; 
CREATE TABLE `permission` ( 
 `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '權限id', 
 `permission_name` varchar(32) DEFAULT NULL COMMENT '權限名', 
 `permission_sign` varchar(128) DEFAULT NULL COMMENT '權限標識,程序中判斷使用,如"user:create"', 
 `description` varchar(256) DEFAULT NULL COMMENT '權限描述,UI界面顯示使用', 
 PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='權限表'; 
/*Data for the table `permission` */ 
insert into `permission`(`id`,`permission_name`,`permission_sign`,`description`) values (1,'用戶新增','user:create',NULL); 
/*Table structure for table `role` */ 
DROP TABLE IF EXISTS `role`; 
CREATE TABLE `role` ( 
 `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '角色id', 
 `role_name` varchar(32) DEFAULT NULL COMMENT '角色名', 
 `role_sign` varchar(128) DEFAULT NULL COMMENT '角色標識,程序中判斷使用,如"admin"', 
 `description` varchar(256) DEFAULT NULL COMMENT '角色描述,UI界面顯示使用', 
 PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='角色表'; 
/*Data for the table `role` */ 
insert into `role`(`id`,`role_name`,`role_sign`,`description`) values (1,'admin','admin','管理員'); 
/*Table structure for table `role_permission` */ 
DROP TABLE IF EXISTS `role_permission`; 
CREATE TABLE `role_permission` ( 
 `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '表id', 
 `role_id` bigint(20) unsigned DEFAULT NULL COMMENT '角色id', 
 `permission_id` bigint(20) unsigned DEFAULT NULL COMMENT '權限id', 
 PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='角色與權限關聯表'; 
/*Data for the table `role_permission` */ 
insert into `role_permission`(`id`,`role_id`,`permission_id`) values (1,2,1); 
/*Table structure for table `user` */ 
DROP TABLE IF EXISTS `user`; 
CREATE TABLE `user` ( 
 `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用戶id', 
 `username` varchar(50) DEFAULT NULL COMMENT '用戶名', 
 `password` char(64) DEFAULT NULL COMMENT '密碼', 
 `state` varchar(32) DEFAULT NULL COMMENT '狀態', 
 `create_time` datetime DEFAULT NULL COMMENT '創建時間', 
 PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='用戶表'; 
/*Data for the table `user` */ 
insert into `user`(`id`,`username`,`password`,`state`,`create_time`) values (1,'starzou','8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92',NULL,'2014-07-17 12:59:08'); 
/*Table structure for table `user_role` */ 
DROP TABLE IF EXISTS `user_role`; 
CREATE TABLE `user_role` ( 
 `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '表id', 
 `user_id` bigint(20) unsigned DEFAULT NULL COMMENT '用戶id', 
 `role_id` bigint(20) unsigned DEFAULT NULL COMMENT '角色id', 
 PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='用戶與角色關聯表'; 
/*Data for the table `user_role` */ 
insert into `user_role`(`id`,`user_id`,`role_id`) values (1,1,1); 
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; 
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; 
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; 
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; 
copyright © 萬盛學電腦網 all rights reserved