框架:SpringMVC – Spring –Mybatis – Maven – redis缓存-Mysql

来源:互联网 发布:汽车零部件出口数据 编辑:程序博客网 时间:2024/05/29 16:27





一.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>com.pj.project</groupId>
<artifactId>baseproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<name>baseproject</name>
<url>http://maven.apache.org</url>


<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>4.11</junit.version>
<struts2.version>2.3.16.3</struts2.version>
<spring.version>4.2.3.RELEASE</spring.version>
<slf4j.version>1.7.13</slf4j.version>
<log4j.version>1.2.17</log4j.version>
<jackson.version>2.6.4</jackson.version>
<mybatis.version>3.3.0</mybatis.version>
<mybatis-spring.version>1.2.3</mybatis-spring.version>
<mysql-jdbc.version>5.1.37</mysql-jdbc.version>
<commons-dbcp.version>1.2.2</commons-dbcp.version>
<freemarker.version>2.3.20</freemarker.version>
<dom4j.version>1.6.1</dom4j.version>


<commons-lang.version>2.5</commons-lang.version>
<commons-io.version>2.2</commons-io.version>
<commons-fileupload.version>1.3.1</commons-fileupload.version>
<commons-beanutils.version>1.8.0</commons-beanutils.version>
<commons-chain.version>1.2</commons-chain.version>
<commons-collections.version>3.1</commons-collections.version>
<commons-digester.version>2.0</commons-digester.version>
<commons-lang3.version>3.1</commons-lang3.version>
<commons-validator.version>1.3.1</commons-validator.version>
<commons-logging.version>1.1.3</commons-logging.version>
<commons-codec.version>1.6</commons-codec.version>
<commons-httpclient.version>3.0.1</commons-httpclient.version>


</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- struts <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> 
<version>${struts2.version}</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> 
<artifactId>struts2-config-browser-plugin</artifactId> <version>${struts2.version}</version> 
</dependency> -->


<!-- spring核心包 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>
<!-- spring核心包 end -->

<!-- 映入JSON -->
<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>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>

<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>


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


<!-- mysql-jdbc -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-jdbc.version}</version>
</dependency>


<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>${commons-dbcp.version}</version>
</dependency>


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


<!-- log日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>


<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>${dom4j.version}</version>
</dependency>


<!-- commons -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>${commons-beanutils.version}</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>${commons-logging.version}</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>${commons-collections.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>${commons-httpclient.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>


<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>

<dependency>
<groupId> org.aspectj</groupId>
<artifactId> aspectjweaver</artifactId>
<version> 1.6.11</version>
</dependency>


<!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.39</version>
</dependency>


<!-- hibernate验证 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>


<!-- spring-redis实现 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.2.RELEASE</version>
</dependency>
<!-- redis客户端jar -->
<dependency>  
            <groupId>redis.clients</groupId>  
            <artifactId>jedis</artifactId>  
            <version>2.9.0</version>  
        </dependency> 
<!-- Ehcache实现,用于参考 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.0.0</version>
</dependency>


</dependencies>
<profiles>
<profile>
<id>jdk-1.8</id>
<!-- 另外一种激活方式 -->
<activation>
<activeByDefault>true</activeByDefault>
<jdk>1.8</jdk>
</activation>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>
</profile>
</profiles>
<build>
<defaultGoal>compile</defaultGoal>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<finalName>myChat</finalName>


<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
<compilerArguments>
<verbose />
<bootclasspath>${java.home}/lib/rt.jar;${java.home}/lib/jce.jar</bootclasspath>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>install</id>
<phase>install</phase>
<goals>
<goal>sources</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warName>/</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
<webResources>
<resource>
<directory>${project.basedir}/lib</directory>
<targetPath>WEB-INF/lib</targetPath>
<filtering>false</filtering>
<includes>
<include>**/*.jar</include>
</includes>
</resource>
</webResources>
</configuration>
</plugin>
<!-- 添加 <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> 
<configuration> <source>1.7</source> <target>1.7</target> </configuration> 
<version>3.3</version> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> 
<artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> 
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> 
<version>${mysql-jdbc.version}</version> </dependency> </dependencies> <configuration> -->
<!--配置文件的路径 <configurationFile>${project.basedir}/generatorConfig.xml</configurationFile> 
<overwrite>true</overwrite> </configuration> </plugin> -->
</plugins>
</build>
</project>


二. applicationContextComplete.xmlspring配置文件模板

<?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"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.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/tx 
           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="properties" />
</bean>
<!-- 自动扫描 -->
<context:component-scan base-package="${component.scan.base.package}" />


<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="${jdbc.initialSize}"></property>
<!-- 连接池最大数量 -->
<property name="maxActive" value="${jdbc.maxActive}"></property>
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="${jdbc.maxIdle}"></property>
<!-- 连接池最小空闲 -->
<property name="minIdle" value="${jdbc.minIdle}"></property>
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="${jdbc.maxWait}"></property>
</bean>


<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation">
<value>classpath:spring/mybatis-config.xml</value>
</property>
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="${mybitis.mapperxml.path}"></property>
</bean>


<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="${dao.base.package}" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>


<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>


<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="delete*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="remove*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="insert*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="save*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="update*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="get*" propagation="SUPPORTS" />
<tx:method name="select*" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice>


<!-- aop -->
<aop:config proxy-target-class="true">
<aop:pointcut id="interceptorPointCuts" expression="${aop.pointcut.expression}" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" />
</aop:config>


<bean id="exceptionHandler" class="${exception.handler.class}" />
</beans>  


三.spring-redis-cache.xml  redis二级缓存的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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-4.2.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/util 
http://www.springframework.org/schema/util/spring-util-4.2.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="properties" />
</bean>
<!-- redis数据源 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxTotal" value="${redis.maxActive}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<!-- Spring-redis连接池管理工厂 -->
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}"
p:pool-config-ref="poolConfig" />
<!-- 使用中间类解决RedisCache.jedisConnectionFactory的静态注入,从而使MyBatis实现第三方缓存 -->
<bean id="redisCacheTransfer" class="com.pj.project.cache.RedisCacheTransfer">
<property name="jedisConnectionFactory" ref="jedisConnectionFactory" />
</bean>
</beans>


四,mybatis-config.xml 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>
<!-- 配置mybatis的缓存,延迟加载等等一系列属性 -->
<settings>
<!-- 全局映射器启用缓存 -->
<setting name="cacheEnabled" value="true" />


<!-- 查询时,关闭关联对象即时加载以提高性能 <setting name="lazyLoadingEnabled" value="false" /> -->

<!-- 对于未知的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="true" />


</settings>


</configuration>


五,spring-mvcComplete.xml springmvc配置文件模板

<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/task 
http://www.springframework.org/schema/task/spring-task-3.1.xsd ">


<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="${springMVC.component.scan.base.package}" />
<!-- 开启这个配置,spring才能识别@Scheduled注解 <task:annotation-driven /> -->


<!--避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
</list>
</property>
</bean>
<!-- 配置自定义转换服务器 -->


<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
</bean>
<!-- 启用注解驱动 -->
<mvc:annotation-driven conversion-service="conversionService">
<!-- 字符串转换器 -->
<mvc:message-converters register-defaults="true">
<bean id="messageConverter"
class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" />
</bean>
<bean id="jsonHttpMesaageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</mvc:message-converters>
<!-- 集合参数解析器 -->
<!--<mvc:argument-resolvers> -->
<!--</mvc:argument-resolvers> -->
</mvc:annotation-driven>
<!-- 配置静态文件路径 -->
<mvc:resources mapping="/resource/**" location="/resource/"
cache-period="86400" />
<mvc:resources mapping="/attached/**" location="/attached/"
cache-period="86400" />
<mvc:resources mapping="/jquery/**" location="/jquery/"
cache-period="86400" />
<mvc:resources mapping="/scripts/**" location="/scripts/"
cache-period="86400" />
<mvc:resources mapping="/css/**" location="/css/"
cache-period="86400" />
<mvc:resources mapping="/bootstrap/**" location="/bootstrap/"
cache-period="86400" />
<mvc:resources mapping="/script/**" location="/script/"
cache-period="86400" />
<mvc:resources mapping="/images/**" location="/images/"
cache-period="86400" />


<mvc:default-servlet-handler />
<!-- 配置国际化资源文件 <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 
<property name="basename" value="i18n/jeeshop" /> </bean> -->


<!-- 指定自己定义的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:properties/validation_message</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>
<!-- 验证自定义信息添加结束 -->




<!-- 设置freeMarker配置文件路径 -->
<bean id="freemarkerConfiguration"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="${springMVC.freemarker.properties.file.path}" />
</bean>


<!-- 配置freeMarker模板路径 -->
<bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape" />
<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="freemarkerSettings" ref="freemarkerConfiguration" />
<property name="templateLoaderPath" value="${springMVC.freemarker.templateLoaderPath}" />
<property name="defaultEncoding" value="UTF-8" />
<!-- 全局变量部分 -->
<property name="freemarkerVariables">
<map>
<entry key="xml_escape" value-ref="fmXmlEscape" />
<entry key="currentUser">
<bean
class="com.pj.project.freemarker.freemarkerVariables.CurrentUserGetter" />
</entry>
<entry key="menuList">
<bean
class="com.pj.project.freemarker.freemarkerVariables.MenuListGetter" />
</entry>
</map>
</property>
</bean>


<!--配置jsp视图解析器 -->
<bean id="viewResolverCommon"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".do" /><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 -->
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="order" value="1" />
</bean>
<!-- 配置freeMarker视图解析器 -->
<bean id="frViewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="viewClass" value="${springMVC.freemarker.viewClass}" />
<property name="prefix" value="/" />
<property name="contentType" value="text/html; charset=utf-8" />
<property name="requestContextAttribute" value="request" />
<property name="suffix" value=".ftl" />
<property name="order" value="0" />
</bean>
<!-- 文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>


<!-- velocity配置解析器 <bean id="velocityViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"> 
<property name="suffix" value=".vm" /> <property name="contentType" value="text/html;charset=UTF-8" 
/> -->
<!-- spring的日期格式化 <property name="dateToolAttribute" value="dateTool" /> 
<property name="toolboxConfigLocation" value="/WEB-INF/toolbox.xml" /> <property 
name="order" value="1" /> </bean> -->
<!-- 拦截器 -->
<bean id="authorizerInterceptor" class="${springMVC.interceptors.authorizerInterceptor.class}">
<property
name="${springMVC.interceptors.authorizerInterceptor.property.name}"
value="${springMVC.interceptors.authorizerInterceptor.property.value}" />
</bean>
<mvc:interceptors>
<ref bean="authorizerInterceptor" />
</mvc:interceptors>
<bean id="exceptionHandler" class="${springMVC.exception.handler.class}" />


</beans>


六,jdbc.properties jdbc属性文件

#mysql
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/project
jdbc.username=root
jdbc.password=123456
jdbc.initialSize=5
jdbc.maxActive=20 
jdbc.maxIdle=20
jdbc.minIdle=1
jdbc.maxWait=60000


七,redis.properties redis属性配置文件

# Redis settings  
redis.host=192.168.1.4
redis.port=6379  
redis.pass=admin


redis.maxIdle=300  
redis.maxActive=600  
redis.maxWait=1000  
redis.testOnBorrow=true  


八.spring.xml 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"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.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/tx 
           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- 引入数据库配置文件 -->
<bean id="properties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:properties/jdbc.properties</value>
<value>classpath:properties/redis.properties</value>
</list>
</property>
</bean>




<import resource="applicationContext.xml" />
<import resource="spring-redis-cache.xml" />
</beans>  


九,internal.properties 项目初始化参数属性文件

#templatePath applicationContext.xml模板文件地址
applicationContext.xml.templatePath=spring/applicationContextComplete.xml
applicationContext.xml.newfilePath=spring/applicationContext.xml


springmvc.xml.templatePath=spring/spring-mvcComplete.xml
springmvc.xml.newfilePath=spring/spring-mvc.xml


#applicationContext.xml文件配置
#jdbc属性文件
configRealm.locations.jdbc.propertyPath=classpath:properties/jdbc.properties
#自动扫描 
component.scan.base.package=com.pj.project
#mybitis mappper.xml path 自动扫描mapping.xml文件,(注意:项目中必须有com.pj.project.entity.mapping包)
mybitis.mapperxml.path=classpath:com/pj/project/entity/mapping/*.xml
# DAO接口所在包名 (注意:项目中必须有com.pj.project.dao包)
dao.base.package=com.pj.project.dao
#aop 切点执行表达式
aop.pointcut.expression=execution(public * com.pj.project.services..*.*(..))
#异常处理类  (注意:项目中必须有com.pj.project.exception.ExceptionHandler类)
exception.handler.class=com.pj.project.exception.ExceptionHandler




#SpringMVC中配置属性
springMVC.component.scan.base.package=com.pj.project.controller
#freemarker配置属性文件路径
springMVC.freemarker.properties.file.path=classpath:properties/freemarker.properties
#配置freeMarker模板路径
springMVC.freemarker.templateLoaderPath=/
#freeMarker视图解析器 
springMVC.freemarker.viewClass=com.pj.project.freemarker.FreemarkerView


#拦截器
springMVC.interceptors.authorizerInterceptor.class=com.pj.project.interceptor.AuthorizerInterceptor
springMVC.interceptors.authorizerInterceptor.property.name=ignorurl
springMVC.interceptors.authorizerInterceptor.property.value=login,regist
#异常处理类
springMVC.exception.handler.class=com.pj.project.exception.ExceptionHandler


十,log4j.properties 日志属性文件

#\u5B9A\u4E49LOG\u8F93\u51FA\u7EA7\u522B  
log4j.rootLogger=INFO,Console,File
#\u5B9A\u4E49\u65E5\u5FD7\u8F93\u51FA\u76EE\u7684\u5730\u4E3A\u63A7\u5236\u53F0  
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.Target=System.out  
#\u53EF\u4EE5\u7075\u6D3B\u5730\u6307\u5B9A\u65E5\u5FD7\u8F93\u51FA\u683C\u5F0F\uFF0C\u4E0B\u9762\u4E00\u884C\u662F\u6307\u5B9A\u5177\u4F53\u7684\u683C\u5F0F  
log4j.appender.Console.layout = org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  
  
#\u6587\u4EF6\u5927\u5C0F\u5230\u8FBE\u6307\u5B9A\u5C3A\u5BF8\u7684\u65F6\u5019\u4EA7\u751F\u4E00\u4E2A\u65B0\u7684\u6587\u4EF6  
log4j.appender.File = org.apache.log4j.RollingFileAppender  
#\u6307\u5B9A\u8F93\u51FA\u76EE\u5F55  
log4j.appender.File.File = E:/myjava/project/myChat/baseproject/logs/ssm.log  
#\u5B9A\u4E49\u6587\u4EF6\u6700\u5927\u5927\u5C0F  
log4j.appender.File.MaxFileSize = 10MB  
# \u8F93\u51FA\u6240\u4EE5\u65E5\u5FD7\uFF0C\u5982\u679C\u6362\u6210DEBUG\u8868\u793A\u8F93\u51FADEBUG\u4EE5\u4E0A\u7EA7\u522B\u65E5\u5FD7  
log4j.appender.File.Threshold = ALL  
log4j.appender.File.layout = org.apache.log4j.PatternLayout  
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n


log4j.logger.org.mybatis.example=DEBUG
log4j.logger.org.mybatis.example.BlogMapper=TRACE 


log4j.logger.org.springframework.web.servlet.mvc=debug


log4j.logger.com.tencent.test=debug
log4j.logger.com.tencent.common=debug
log4j.logger.com.tencent=debug
log4j.logger.com.pj.project=debug


十一,MyContextLoaderListener 自定义spring监听器

public class MyContextLoaderListener extends ContextLoaderListener {
private String propertyFilePath;


public MyContextLoaderListener() {


}


public String getPropertyFilePath() {
return propertyFilePath;
}


public void setPropertyFilePath(String propertyFilePath) {
this.propertyFilePath = propertyFilePath;
}


@Override
public void contextInitialized(ServletContextEvent event) {


initConfigXml(event);
super.contextInitialized(event);
}


public void initConfigXml(ServletContextEvent event) {
propertyFilePath = event.getServletContext().getInitParameter("initPropertyFilePath");
InitSpringXMLUtil util = new InitSpringXMLUtil(propertyFilePath);
util.creatApplicationContext();
util.creatSpringMvc();
}


}


十二,InitSpringXMLUtil  初始化spring配置文件工具类

package com.pj.project.util;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Properties;


import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 初始化spring applicationContext.xml spring-mvc.xml
 * 
 * @author pujin
 *
 */
public class InitSpringXMLUtil {


private static final Logger logger = LoggerFactory.getLogger(InitSpringXMLUtil.class);


private static Properties properties;


private static String propertyFilePath;
private static String classrootpath = InitSpringXMLUtil.class.getClassLoader().getResource("").getPath();


public InitSpringXMLUtil(String propertyFilePath) {
InitSpringXMLUtil.propertyFilePath = propertyFilePath;
}


public void creatApplicationContext() {
String templatePath = getProperties().getProperty("applicationContext.xml.templatePath");
String newfilePath = getProperties().getProperty("applicationContext.xml.newfilePath");
createXml(templatePath, newfilePath);
}


public void creatSpringMvc() {
String templatePath = getProperties().getProperty("springmvc.xml.templatePath");
String newfilePath = getProperties().getProperty("springmvc.xml.newfilePath");
createXml(templatePath, newfilePath);
}


public static Properties getProperties() {
if (properties == null) {


properties = getProperties(propertyFilePath);
}
return properties;


}


public static Properties getProperties(String propertyFilePath) {
try {
if (!propertyFilePath.contains(":/")) {
propertyFilePath = classrootpath + propertyFilePath;
}
LoggerUtil.logInfo(logger, "propertyFilePath=" + propertyFilePath);
System.out.println("propertyFilePath=" + propertyFilePath);
Properties pps = new Properties();
InputStream in = new BufferedInputStream(new FileInputStream(propertyFilePath));
pps.load(in);


return pps;


} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}


/**
* 创建applicationContext。xml文件

* @param templatePath
*            模板地址
*            E:/myjava/project/myChat/baseproject/src/main/resources/spring/applicationContext.xml
* @param newfilePath
*            生成文件地址
*            E:/myjava/project/myChat/baseproject/src/main/resources/spring/applicationContext2.xml
*/
public static void createXml(String templatePath, String newfilePath) {
try {


if (!templatePath.contains(":/")) {
templatePath = classrootpath + templatePath;
}
if (!newfilePath.contains(":/")) {
newfilePath = classrootpath + newfilePath;
}
// 创建Document对象,读取已存在的Xml文件person.xml
Document doc = new SAXReader().read(new File(templatePath));


updateXMLElement(doc);


// 指定文件输出的位置
FileOutputStream out = new FileOutputStream(newfilePath);
// 指定文本的写出的格式:
OutputFormat format = OutputFormat.createPrettyPrint(); // 漂亮格式:有空格换行
format.setEncoding("UTF-8");
// 1.创建写出对象
XMLWriter writer = new XMLWriter(out, format);
// 2.写出Document对象
writer.write(doc);
// 3.关闭流
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


public static void updateXMLElement(Document doc) {
Element root = doc.getRootElement();
updateXmlElemet(root);
}


@SuppressWarnings("unchecked")
public static void updateXmlElemet(Element root) {
Iterator<Element> it = root.elementIterator();
while (it.hasNext()) {
Element element = it.next();
Attribute ca = element.attribute("id");
if (ca != null && "dataSource".equals(ca.getValue())) {
continue;
}
Iterator<Attribute> attrIt = element.attributeIterator();
while (attrIt.hasNext()) {
Attribute a = attrIt.next();
String av = a.getValue();
if (checkPlaceholder(av)) {
String value = getPlaceholderValue(av);
System.out.println(value);
value = getProperties().getProperty(value);
a.setValue(value);
}


}
if (element.isTextOnly()) {
String ev = element.getStringValue();
if (checkPlaceholder(ev)) {
String value = getPlaceholderValue(ev);
value = getProperties().getProperty(value);
element.setText(value);
}
}
Iterator<Element> is = element.elementIterator();
if (is.hasNext()) {
updateXmlElemet(element);
}


}
}


/**
* 判断是否为占位符

* @param str
* @return
*/
public static boolean checkPlaceholder(String str) {
if (str == null || str == "") {
return false;
}
String prefix = "${";
boolean start = str.startsWith(prefix);
String suffix = "}";
boolean end = str.endsWith(suffix);
if (start && end) {
return true;
}
return false;
}


/**
* 获取暂未发字段

* @param str
* @return
*/
public static String getPlaceholderValue(String str) {
return str.substring(2, str.length() - 1);
}


public static String getPropertyFilePath() {
return propertyFilePath;
}


public static void setPropertyFilePath(String propertyFilePath) {
InitSpringXMLUtil.propertyFilePath = propertyFilePath;
}


}


十三,web.xml 服务器启动文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="myChatWebApp" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" 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">


<display-name>baseproject</display-name>
<description>Community application by Network</description>


<!-- 设置请求编码 -->
<filter>
<filter-name>springMVCEncoding</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>springMVCEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring/spring.xml</param-value>
</context-param>


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


<!-- Spring监听器 -->
<context-param>
<param-name>initPropertyFilePath</param-name>
<param-value>properties/internal.properties</param-value>
</context-param>
<listener>
<listener-class>com.pj.project.spring.MyContextLoaderListener</listener-class>
</listener>


<!-- 日志log4j -->
<!-- 设置由Sprng载入的Log4j配置文件位置 -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:properties/log4j.properties</param-value>
</context-param>
<!-- Spring刷新Log4j配置文件变动的间隔,单位为毫秒 -->
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>10000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>


<listener>
<listener-class>com.pj.project.listener.SystemListener</listener-class>
</listener>
<!-- 如果实现用户一段时间内不操作,销毁session的话要在web.xml中配置session超时 -->
<session-config>
<session-timeout>1000</session-timeout>
</session-config>


<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/404.jsp</location>
</error-page>
</web-app>



阅读全文
1 0