基于Spring + Spring MVC + Mybatis 高性能web构建实例详解
一直想写这篇文章,前段时间痴迷于javascript、nodejs、angularjs,做了大量的研究,对前后端交互有了更深层次的认识。
今天抽个时间写这篇文章,我有预感,这将是一篇很详细的文章,详细的配置,详细的注释,看起来应该很容易懂。
用最合适的技术去实现,并不断追求最佳实践。这就是架构之道。
希望这篇文章能给你们带来一些帮助,同时希望你们可以为这个项目贡献你的想法。
源码地址:https://github.com/eliteams/quick4j 点击打开
源码地址:https://github.com/eliteams/quick4j 点击打开
源码地址:https://github.com/eliteams/quick4j 点击打开
看我们的项目结构:
是一个典型的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 */;
以上所述是小编给大家介绍的基于spring + spring mvc + mybatis 高性能web构建实例详解,希望对大家有所帮助
上一篇: 数据课程设计 -——-校园导航系统