本次介绍spring+springMVC+hibernate+druid+log4j的配置
所有的配置文件都放在maven创建的项目 src\main\resources 文件夹下
一、下载各个框架的相关JAR文件(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.ge</groupId>
<artifactId>ssh</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>ssh Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>4.12</junit.version>
<log4j.version>1.2.17</log4j.version>
<slf4j.version>1.7.25</slf4j.version>
<spring.version>4.3.14.RELEASE</spring.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<hibernate.validator.version>5.4.1.Final</hibernate.validator.version>
<aspect.version>1.8.9</aspect.version>
<jstl.version>1.2</jstl.version>
<jackson.version>2.9.5</jackson.version>
<mysql.version>5.1.38</mysql.version>
<druid.version>1.1.10</druid.version>
<commons.io.version>2.4</commons.io.version>
<commons.fileupload.version>1.3.1</commons.fileupload.version>
<ehcache.version>2.10.6</ehcache.version>
</properties>
<dependencies>
<!-- 引入spring框架与ehcache框架的兼容JAR包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 引入ehcache二级缓存相关JAR包 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>${ehcache.version}</version>
</dependency>
<!-- 引入文件上传需要的JAR包 -->
<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>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- 引入springmvc框架的相关JAR包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 引入hibernate的验证框架 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate.validator.version}</version>
</dependency>
<!-- 引入jstl,springmvc才能识别标准标签库 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- 引入slf4j日志标准,作用:适配其他具体的日志框架,如:log4j,logback…… -->
<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>
<!-- 导入jackson工具JAR包 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- 引入第3方的切面框架AspectJrt的相关JAR文件 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspect.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspect.version}</version>
</dependency>
<!-- 引入与mysql连接的驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- 导入spring容器相关JAR文件 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 导入spring容器整合ORM框架的相关JAR文件 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 引入spring框架兼容Junit单元测试框架的相关JAR包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- 导入junit单元测试框架JAR包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- 导入LOG4J日志框架JAR包 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- 导入hibernate持久层框架JAR包 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
</dependencies>
<build>
<finalName>ssh</finalName>
<pluginManagement>
<!-- 配置maven 在构建项目时,采用相关插件 -->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
二、根据需求分析设计阶段的设计结果,完成项目的包结构,以及类结构
三、编写对应的配置文件,applicationContext.xml,spring-mvc.xml,log4j.properties,web.xml,mysql.properties
log4j.properties也可以换成log4j.xml
mysql.properties配置(配置与数据库的连接信息)
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF8&allowMultiQueries=true
jdbc.username=root
jdbc.password=1234
applicationContext.xml配置(配置的是业务层以下)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:cache="http://www.springframework.org/schema/cache"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<!-- 第1步:开启spring容器的自动扫描功能 -->
<context:component-scan base-package="com.ge.ssh">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 第2步:引入外部的数据库配置描述文件 -->
<context:property-placeholder location="classpath:mysql.properties" />
<!-- 第3步:配置数据源连接池:C3P0,DBCP2,DRUID -->
<!-- destroy-method="close" 该方法代表spring容器在销毁时,需要调用close(),关闭掉所有的数据库连接对象 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<!-- 配置连接数据库最基本的3元素 (驱动可忽略) -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 最大连接数 -->
<property name="maxActive" value="20" />
<!-- 初始化数量 -->
<property name="initialSize" value="1" />
<!-- 创建连接的超时时间,单位:毫秒 -->
<property name="maxWait" value="60000" />
<!-- 最小连接数 -->
<property name="minIdle" value="1" />
<!-- 配置校验语句 -->
<property name="validationQuery" value="select now() from dual" />
<!-- 配置校验(连接空闲时,借出时,归还时) -->
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<!-- 配置是否允许PreparedStatements对象的缓存 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxOpenPreparedStatements" value="20" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<!-- 配置连接池中,创建连接时,采用异步|同步方式来进行创建,默认是:异步 -->
<property name="asyncInit" value="true" />
<!-- 配置额外的扩展插件:stat 代表开启监控程序,wall 代表开启防SQL注入功能 -->
<property name="filters" value="wall" />
<!-- 如果有定制化的过滤器,可以使用proxyFilters 去做一个引用 -->
<property name="proxyFilters">
<list>
<ref bean="stat-filter" />
<ref bean="log-filter" />
</list>
</property>
</bean>
<!-- 定制化的监控过滤器 -->
<bean id="stat-filter" class="com.alibaba.druid.filter.stat.StatFilter">
<property name="slowSqlMillis" value="200" />
<property name="logSlowSql" value="true" />
</bean>
<!-- 定制化的日志过滤器 -->
<bean id="log-filter" class="com.alibaba.druid.filter.logging.Log4jFilter">
<!-- 开启数据源相关的日志记录 -->
<property name="dataSourceLogEnabled" value="true" />
<!-- 连接错误时,记录相关日志 -->
<property name="connectionLogErrorEnabled" value="true"></property>
<!-- 预编译对象,发生错误时记录相关日志 -->
<property name="statementLogErrorEnabled" value="true"></property>
</bean>
<!-- 第4步,配置SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 开启自动扫描功能,扫描使用JPA规范(注解),完成ORM映射关系的实体类 -->
<property name="packagesToScan">
<array>
<value>com.gezhi.ssh.bean</value>
<!-- <value>com.ge.sh.bean02</value> -->
</array>
</property>
<!-- 假设你们公司,还在用XML完成ORM映射,那么就应该采用如下方式,完成注册 -->
<!-- <property name="mappingResources"> <array> <value>com/ge/sh/xmls/UserBean.hbm.xml</value>
</array> </property> -->
<!-- 配置跟 hibernate 相关的一些配置 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<!-- 第5步,配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置hibernate模板操作类 -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 第6步,配置spring管理事务的2种方式:编程式事务管理,声明式事务管理 -->
<!-- 编程式事务管理 需要在业务类中,借助TransactionTemplate,PlatformTransactionManager 完成对业务逻辑
的逻辑事务管理 -->
<!-- 声明式事务管理,第1种方式,采用AOP管理业务逻辑事务 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" read-only="true" propagation="SUPPORTS" />
<tx:method name="save*" read-only="false" rollback-for="java.lang.Exception"
propagation="REQUIRED" />
<tx:method name="add*" read-only="false" rollback-for="java.lang.Exception"
propagation="REQUIRED" />
<tx:method name="insert*" read-only="false" rollback-for="java.lang.Exception"
propagation="REQUIRED" />
<tx:method name="create*" read-only="false" rollback-for="java.lang.Exception"
propagation="REQUIRED" />
<tx:method name="update*" read-only="false" rollback-for="java.lang.Exception"
propagation="REQUIRED" />
<tx:method name="modify*" read-only="false" rollback-for="java.lang.Exception"
propagation="REQUIRED" />
<tx:method name="change*" read-only="false" rollback-for="java.lang.Exception"
propagation="REQUIRED" />
<tx:method name="delete*" read-only="false" rollback-for="java.lang.Exception"
propagation="REQUIRED" />
<tx:method name="remove*" read-only="false" rollback-for="java.lang.Exception"
propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="txMagPoint"
expression="execution(* com.ge.ssh.*mag.service.impl.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="txMagPoint" />
</aop:config>
<!-- 声明式事务管理,第2种方式,使用@Transactional管理业务逻辑事务 -->
<!-- 开启事务的注解支持 -->
<!-- <tx:annotation-driven transaction-manager="transactionManager"/> -->
<!-- 第7步,开启切面动态代理支持 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!-- 第8步(非必须),spring整合ehcache 开始 -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cache-manager-ref="ehcache" />
<bean id="ehcache"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:config-location="classpath:ehcache.xml" />
<!-- 开启spring的注解缓存支持 -->
<cache:annotation-driven />
<!-- spring整合ehcache 结束 -->
<!-- 第9步(非必须),配置druid支持spring监控(监控业务代码处理时间) -->
<bean id="druid-stat-interceptor"
class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
</bean>
<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut"
scope="prototype">
<property name="patterns">
<list>
<value>com.ge.ssh.*mag.service.impl.*</value>
</list>
</property>
</bean>
<aop:config>
<aop:advisor advice-ref="druid-stat-interceptor"
pointcut-ref="druid-stat-pointcut" />
</aop:config>
</beans>
chcache.xml配置(用了缓存才进行配置)
<ehcache>
<!-- 定义缓存数据存放的位置:java.io.tmpdir (默认为内存空间),如果要修改位置:/home/lilinhan/ d:/ehcache -->
<diskStore path="java.io.tmpdir"/>
<!-- 定义默认的缓存配置 -->
<cache
name="users"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
memoryStoreEvictionPolicy="LRU"
/>
<!-- maxElementsInMemory="10000" 定义缓存中,可以存放数据的数据量 -->
<!-- eternal="false" 设置存放的元素是否是"常量" -->
<!-- timeToIdleSeconds="120" 设置元素在缓存空间中,不使用的情况下,默认的存活时间,单位是:秒 -->
<!-- timeToLiveSeconds="120" 设置元素在缓存空间中,如果发生调用,需要重置的存活时间(只重置1次),单位是:秒 -->
<!-- overflowToDisk="true" 当内存不足存储10000多个对象时,是否启动硬盘存储 -->
<!-- memoryStoreEvictionPolicy="LRU" 设置缓存清理策略:LRU 最近最少使用 LFU 最少使用 FIFO 先进先出 -->
<cache name="roles"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
memoryStoreEvictionPolicy="LRU"
/>
</ehcache>
spring-mvc.xml配置(配置的是表现层的东西)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.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">
<!-- 开启spring容器的自动扫描功能 -->
<context:component-scan base-package="com.ge.ssh">
<!-- context:exclude-filter 排除过滤器 -->
<!-- context:include-filter 包含过滤器 -->
<!-- 定义容器在扫描时,需要排除组件的过滤器, 过滤器的类型有:annotation(注解),assignable(类),aspectj(切面),regex(正则过滤器) -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Service" />
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Repository" />
</context:component-scan>
<!-- 开启springmvc的注解支持 -->
<mvc:annotation-driven conversion-service="conversionService"
validator="localValidatorFactoryBean">
<mvc:message-converters>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json; charset=UTF-8</value>
<value>application/x-www-form-urlencoded; charset=UTF-8</value>
</list>
</property>
<!-- 配置 objectMapper 为我们自定义扩展后的 CustomMapper -->
<property name="objectMapper">
<bean class="com.ge.ssh.util.CustomMapper"></bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 指定静态资源文件的位置 -->
<mvc:resources location="/static/" mapping="/static/**"></mvc:resources>
<!-- 定义spring框架的转换工厂,并且向转换工厂中注册"自定义的转换器" -->
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.ge.ssh.converter.StringToDateConverter"></bean>
</set>
</property>
</bean>
<!-- 配置spring框架提供的验证工厂,并告知我们验证框架使用的是Hibernate 提供的验证框架 -->
<bean id="localValidatorFactoryBean"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
</bean>
<!-- 配置文件上传解析器,ID固定为:multipartResolver -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置每次最大允许上传100M的内容,单位是:byte -->
<property name="maxUploadSize" value="104857600"></property>
<!-- 设置每次单个文件,最大允许上传10M的内容,单位是:byte -->
<property name="maxUploadSizePerFile" value="10485760"></property>
<!-- 设置解析文件时,采用utf-8的字符集进行编码 -->
<property name="defaultEncoding" value="utf-8"></property>
<!-- 保留源文件的名称 -->
<property name="preserveFilename" value="true"></property>
</bean>
<!-- 配置视图解析器 -->
<bean id="internalResourceViewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<!-- 前缀 -->
<property name="prefix" value="/"></property>
<!-- 后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
在上述配置文件的“开启springmvc的注解支持”中端配置中,可以注意到我们配置了一个CustomMapper,这个是用来替换objectMapper的,因为我们要向前端返回json数据,表现层中,调用底层接口的时候,因为有延时加载(懒加载),比如我们做查询的时候,第一次查询结束后,还没有开始第二次的懒加载操作的时候,作为的时候这时候objectMapper就将我们的对象进行序列化了,而这时候关联对象还没有进行查找,所以关联对象的属性就为空,这时候就会报,因为属性为空,无法序列化的错误。
CustomMapper继承自objectMapper,代码如下:
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
* 自定义Jackson中的核心解析类
* @author Administrator
*
*/
public class CustomMapper extends ObjectMapper{
/**
*
*/
private static final long serialVersionUID = -431687360027624006L;
public CustomMapper() {
this.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 设置 SerializationFeature.FAIL_ON_EMPTY_BEANS 为 false
// 如果在序列化对象的空关联对象时,空的关联对象,将不会参与到对象的序列化
this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
}
lg4j.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN" "log4j.dtd">
<log4j:configuration>
<!-- appender 代表输出,用于指定日志输出的位置 -->
<!-- STDOUT 系统启动日志级别 -->
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="conversionPattern" value="%c %d{yyyy-MM-dd hh:mm:ss} %p %m%n"/>
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="levelMin" value="INFO"/>
</filter>
</appender>
<appender name="D" class="org.apache.log4j.RollingFileAppender">
<!-- file 存放的文件名 -->
<param name="file" value="d://logs/ssh-debug.log"/>
<param name="append" value="true"/>
<param name="maxFileSize" value="10240KB"/><!-- maxFileSize 文件的最大容量 -->
<param name="maxBackupIndex" value="10"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="conversionPattern" value="%c %d{yyyy-MM-dd hh:mm:ss} %p %m%n"/>
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="levelMin" value="DEBUG"/>
<param name="levelMax" value="DEBUG"/>
</filter>
</appender>
<appender name="I" class="org.apache.log4j.RollingFileAppender">
<!-- file 存放的文件名 -->
<param name="file" value="d://logs/ssh-info.log"/>
<param name="append" value="true"/>
<param name="maxFileSize" value="10240KB"/><!-- maxFileSize 文件的最大容量 -->
<param name="maxBackupIndex" value="10"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="conversionPattern" value="%c %d{yyyy-MM-dd hh:mm:ss} %p %m%n"/>
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="levelMin" value="INFO"/>
<param name="levelMax" value="INFO"/>
</filter>
</appender>
<appender name="W" class="org.apache.log4j.RollingFileAppender">
<!-- file 存放的文件名 -->
<param name="file" value="d://logs/ssh-warn.log"/>
<param name="append" value="true"/>
<param name="maxFileSize" value="10240KB"/><!-- maxFileSize 文件的最大容量 -->
<param name="maxBackupIndex" value="10"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="conversionPattern" value="%c %d{yyyy-MM-dd hh:mm:ss} %p %m%n"/>
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="levelMin" value="WARN"/>
<param name="levelMax" value="WARN"/>
</filter>
</appender>
<appender name="E" class="org.apache.log4j.RollingFileAppender">
<!-- file 存放的文件名 -->
<param name="file" value="d://logs/ssh-error.log"/>
<param name="append" value="true"/>
<param name="maxFileSize" value="10240KB"/><!-- maxFileSize 文件的最大容量 -->
<param name="maxBackupIndex" value="10"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="conversionPattern" value="%c %d{yyyy-MM-dd hh:mm:ss} %p %m%n"/>
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="levelMin" value="ERROR"/>
<param name="levelMax" value="ERROR"/>
</filter>
</appender>
<appender name="druid" class="org.apache.log4j.RollingFileAppender">
<!-- file 存放的文件名 -->
<param name="file" value="d://logs/druid-slow-sql.log"/>
<param name="append" value="true"/>
<param name="maxFileSize" value="10240KB"/><!-- maxFileSize 文件的最大容量 -->
<param name="maxBackupIndex" value="10"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="conversionPattern" value="%c %d{yyyy-MM-dd hh:mm:ss} %p %m%n"/>
</layout>
<filter class="com.ge.ssh.filter.DruidLogAcceptFilter">
<param name="keyword" value="com.alibaba"/>
<param name="level" value="ERROR"/>
</filter>
</appender>
<root>
<priority value="INFO"></priority>
<appender-ref ref="console"/>
<appender-ref ref="D"/>
<appender-ref ref="I"/>
<appender-ref ref="W"/>
<appender-ref ref="E"/>
<appender-ref ref="druid"/>
</root>
</log4j:configuration>
对于日志文件的记录中,因为开启了druid的监控日志,所以,在druid-slow-sql.log日志文件中只显示相关的信息,所以需要排除其他信息,这里就调用了DruidLogAcceptFilter过滤器,代码如下:
import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggingEvent;
public class DruidLogAcceptFilter extends Filter {
private String keyword;
private Level level;
@Override
public int decide(LoggingEvent event) {
// TODO Auto-generated method stub
// 得到正在记录日志的类的类名
String msg = event.getLocationInformation().getClassName();
if (msg.contains(keyword) && event.getLevel() == level) {
return Filter.ACCEPT;
} else {
return Filter.DENY;
}
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public Level getLevel() {
return level;
}
public void setLevel(Level level) {
this.level = level;
}
}
web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<!-- 利用后面配置的监听器,在容器启动时就去加载该文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- <context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param> -->
<!-- 利用后面配置的监听器,在容器启动时就去加载该文件-->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.xml</param-value>
</context-param>
<!-- spring容器间隔1分钟,扫描一次log4j.properties文件或log4j.xml文件的变化 -->
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>60000</param-value>
</context-param>
<!-- 配置一系列的过滤器 -->
<!-- 配置OpenSessionInViewFilter 的作用:在同一个视图范围内, 发起的一次请求范围内,Session的生命周期与处理该请求的线程生命周期,保持一致,Session不关闭,
当请求正常处理完成了,然后在关闭Session,从而解决懒加载过程中的no session问题 -->
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<!-- 配置字符编码过滤器 -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>com.ge.ssh.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>
<!-- 配置DRUID的监控程序,需要排除如下uri发过来的请求(例如:不需要针对.js这种请求,进行监控) -->
<filter>
<filter-name>druidWebStatFilter</filter-name>
<filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
<init-param>
<param-name>exclusions</param-name>
<param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
</init-param>
</filter>
<!-- 配置PUT支持表单提交过滤器 -->
<filter>
<filter-name>httpPutFormContentFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<!-- 配置表单支持PUT,DELETE提交的过滤器 -->
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter>
<filter-name>httpPUTOrDelete2GetFilter</filter-name>
<filter-class>com.ge.ssh.filter.HttpPUTOrDelete2GetFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<servlet-name>centerController</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>druidWebStatFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>httpPutFormContentFilter</filter-name>
<servlet-name>centerController</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<servlet-name>centerController</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>httpPUTOrDelete2GetFilter</filter-name>
<servlet-name>centerController</servlet-name>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<!-- 通过监听器,开启其他层的spring容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 通过前端控制器,开启WEB层的spring容器 -->
<servlet>
<servlet-name>centerController</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>
</servlet>
<!-- 开启Druid的内置监控页面 -->
<servlet>
<servlet-name>druidStatView</servlet-name>
<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
<init-param>
<!-- 允许清空统计数据 -->
<param-name>resetEnable</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<!-- 允许访问监听系统IP地址(白名单) -->
<param-name>allow</param-name>
<param-value>127.0.0.1</param-value>
</init-param>
<init-param>
<!-- 用户名 -->
<param-name>loginUsername</param-name>
<param-value>admin</param-value>
</init-param>
<init-param>
<!-- 密码 -->
<param-name>loginPassword</param-name>
<param-value>123456</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>centerController</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 监控地址:http://localhost/ssh/druid/login.html -->
<servlet-mapping>
<servlet-name>druidStatView</servlet-name>
<url-pattern>/druid/*</url-pattern>
</servlet-mapping>
</web-app>