參考博客:http://blog.csdn.net/wp1603710463/article/details/50839036
http://sunney2010.iteye.com/blog/1404729

pom
<properties>
<spring.version>4.3.5.RELEASE</spring.version>
<mybatis.version>3.4.1</mybatis.version>
<mybatis-spring.version>1.3.1</mybatis-spring.version>
<oracle.version>11.1.0.7.0</oracle.version>
<mysql.version>5.1.10</mysql.version>
<!-- druid 版本號 -->
<druid.version>1.0.29</druid.version>
<dbcp.version>1.2.2</dbcp.version>
<c3p0.version>0.9.1.2</c3p0.version>
<!--日志 s-->
<logback.version>1.2.3</logback.version>
<slf4j.version>1.7.7</slf4j.version>
<!--日志 s-->
</properties>
<dependencies>
<!--整合spring框架s-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring織入-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.2</version>
</dependency>
<!--整合spring框架s-->
<!-- 整合mybatis和mybatis和spring整合包 s-->
<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和mybatis和spring整合包 s-->
<!-- 整合數據庫連接池 s-->
<!--druid 連接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>${dbcp.version}</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
<!-- 整合數據庫連接池 e-->
<!-- 數據庫驅動 -->
<dependency>-->
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>${oracle.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- 第三方常用jar包 -->
<!--日志 logback + slf4j start-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<!-- logback + slf4j end -->
<!--解決數據量大的問題-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<!--解決數據量大的問題-->
<!--報表-->
<dependency>
<groupId>jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.0.13</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--文件上傳-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jstl-impl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.4.2</version>
</dependency>
<!-- 防止和tomcat中的jar沖突 -->
<!--<dependency>-->
<!--<groupId>org.apache.tomcat</groupId>-->
<!--<artifactId>servlet-api</artifactId>-->
<!--<version>6.0.33</version>-->
<!--<scope>provided</scope>-->
<!--</dependency>-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-servlet_3.0_spec</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>ssm2017</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
2.druid.properties
driverClassName:com.mysql.jdbc.Driver db-key-170=dataSource-170 db-key-236=dataSource-236 db-key-225=dataSource-225 url:jdbc:mysql://192.168.20.170:3306/s?characterEncoding=utf-8 username:root password:qqqqq 170.url:jdbc:mysql://192.168.20.170:3306/s?characterEncoding=utf-8 170.username:root 170.password:cccccc 225.url:jdbc:mysql://192.168.20.225:3306/s2017?characterEncoding=utf-8 225.username:root 225.password:bbbbbbb 236.url:jdbc:mysql://192.168.20.236:3306/s?characterEncoding=utf-8 236.username:root 236.password:123456 filters:stat #監控統計用的filter:stat #日志用的filter:log4j #防御sql注入的filter:wal maxActive:20 initialSize:1 maxWait:60000 minIdle:10 #maxIdle:15 timeBetweenEvictionRunsMillis:60000 minEvictableIdleTimeMillis:300000 maxPoolPreparedStatementPerConnectionSize:20 #用來檢測連接是否有效的sql validationQuery:SELECT 'x' #validationQuery:select 1 from dual testWhileIdle:true testOnBorrow:false testOnReturn:false poolPreparedStatements:true maxOpenPreparedStatements:20 removeAbandoned:true removeAbandonedTimeout:1800 logAbandoned:false
3.logback.xml
4.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang.xsd">
<!-- 加載配置文件 -->
<!--<context:property-placeholder location="classpath:jdbc.properties"/>-->
<!--<context:property-placeholder location="classpath:druid.properties"/>-->
<!-- jdbc數據庫連接池
<bean id="parentDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<!–<property name="url" value="${170.jdbc.url}"/>–>
<!–<property name="username" value="${170.jdbc.username}"/>–>
<!–<property name="password" value="${170.jdbc.password}"/>–>
<!– 開發階段建議最大連接數據盡量少,夠用即可 –>
<property name="maxActive" value="${jdbc.maxActive}"/>
<property name="maxIdle" value="${jdbc.maxIdle}"/>
</bean>-->
<!-- 1. 加載數據庫配置的屬性文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/druid.properties</value>
</list>
</property>
</bean>
<!--2. 數據源dataSource-->
<bean id="parentDataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"
init-method="init">
<!-- 數據庫基本信息配置 -->
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<property name="driverClassName" value="${driverClassName}"/>
<!-- 最大並發連接數 -->
<property name="maxActive" value="${maxActive}"/>
<!-- 初始化連接數量 -->
<property name="initialSize" value="${initialSize}"/>
<!-- 配置獲取連接等待超時的時間 -->
<property name="maxWait" value="${maxWait}"/>
<!-- 最小空閑連接數 -->
<property name="minIdle" value="${minIdle}"/>
<!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}"/>
<!-- 配置一個連接在池中最小生存的時間,單位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}"/>
<property name="validationQuery" value="${validationQuery}"/>
<property name="testWhileIdle" value="${testWhileIdle}"/>
<property name="testOnBorrow" value="${testOnBorrow}"/>
<property name="testOnReturn" value="${testOnReturn}"/>
<!-- 打開PSCache,並且指定每個連接上PSCache的大小 -->
<property name="poolPreparedStatements" value="${poolPreparedStatements}"/>
<property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}"/>
<!-- 打開 removeAbandoned 功能 -->
<property name="removeAbandoned" value="${removeAbandoned}"/>
<!-- 1800 秒,也就是 30 分鍾 -->
<property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}"/>
<!-- 關閉 abanded 連接時輸出錯誤日志 -->
<property name="logAbandoned" value="${logAbandoned}"/>
<property name="filters" value="${filters}"/>
<!-- 解密密碼必須要配置的項 -->
<!--<property name="filters" value="config" />-->
<!--<property name="connectionProperties" value="config.decrypt=true;config.decrypt.key=${publicKey}" />-->
<!-- 這里配置提交方式,默認就是TRUE,可以不用配置 -->
<property name="defaultAutoCommit" value="true"/>
<!-- 驗證連接有效與否的SQL,不同的數據配置不同 -->
<property name="proxyFilters">
<list>
<ref bean="logFilter"/>
</list>
</property>
</bean>
<bean id="logFilter" class="com.alibaba.druid.filter.logging.Slf4jLogFilter">
<property name="statementExecutableSqlLogEnable" value="false"/>
</bean>
<bean id="170dataSource" parent="parentDataSource">
<property name="url" value="${170.url}"/>
<property name="username" value="${170.username}"/>
<property name="password" value="${170.password}"/>
</bean>
<bean id="236dataSource" parent="parentDataSource">
<property name="url" value="${236.url}"/>
<property name="username" value="${236.username}"/>
<property name="password" value="${236.password}"/>
</bean>
<bean id="225dataSource" parent="parentDataSource">
<property name="url" value="${225.url}"/>
<property name="username" value="${225.username}"/>
<property name="password" value="${225.password}"/>
</bean>
<bean id="dataSource" class="cn.lpj.utils.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="${db-key-170}" value-ref="170dataSource"/>
<entry key="${db-key-236}" value-ref="236dataSource"/>
<entry key="${db-key-225}" value-ref="225dataSource"/>
</map>
</property>
</bean>
<!--<bean id="parentDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"-->
<!--destroy-method="close">-->
<!--<property name="url" value="${225.url}"/>-->
<!--<property name="username" value="${225.username}"/>-->
<!--<property name="password" value="${225.password}"/>-->
<!--<property name="driverClassName" value="${driverClassName}"/>-->
<!--<property name="filters" value="${filters}"/>-->
<!--<property name="maxActive" value="${maxActive}"/>-->
<!--<property name="initialSize" value="${initialSize}"/>-->
<!--<property name="maxWait" value="${maxWait}"/>-->
<!--<property name="minIdle" value="${minIdle}"/>-->
<!--<property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}"/>-->
<!--<property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}"/>-->
<!--<property name="validationQuery" value="${validationQuery}"/>-->
<!--<property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}"/>-->
<!--<property name="maxPoolPreparedStatementPerConnectionSize"-->
<!--value="${maxPoolPreparedStatementPerConnectionSize}"/>-->
<!--<property name="testWhileIdle" value="true"/>-->
<!--<property name="testOnBorrow" value="false"/>-->
<!--<property name="testOnReturn" value="false"/>-->
<!--</bean>-->
<!--<bean id="dataSource" parent="parentDataSource">-->
<!--<property name="url" value="${170.url}"/>-->
<!--<property name="username" value="${170.username}"/>-->
<!--<property name="password" value="${170.password}"/>-->
<!--</bean>-->
<!--<bean id="dataSource225" parent="parentDataSource">-->
<!--<property name="url" value="${225.url}"/>-->
<!--<property name="username" value="${225.username}"/>-->
<!--<property name="password" value="${225.password}"/>-->
<!--</bean>-->
<!--<bean id="dataSource236" parent="parentDataSource">-->
<!--<property name="url" value="${236.url}"/>-->
<!--<property name="username" value="${236.username}"/>-->
<!--<property name="password" value="${236.password}"/>-->
<!--</bean>-->
<!-- 配置SqlSessionFactory
從spring和mybatis的整合包中獲取
-->
<!-- 3. SessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加載數據源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 整合mybatis,包掃描 mapper文件 -->
<property name="configLocation" value="classpath:/mybatis/sqlMapConfig.xml"/>
<property name="mapperLocations" value="classpath:/cn/lpj/dao/*Mapper.xml"/>
</bean>
<!--4-->
<!-- 使用MapperFactoryBean 生成mapper的代理對象
在mybatis和spring的整合包中
-->
<!-- <bean id="sysuserCustomMapper" class="org.mybatis.sprdaopper.MapperFactoryBean">
配置mapper接口
<property name="mapperInterface" value="yycg.base.daopper.SysuserCustomMapper"/>
配置sqlSessionFactory
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean> -->
<!--配置 mapper自動掃描器
bean名稱就是mapper類型(首字母小寫)
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置掃描包路徑 ,如果掃描多個包路徑,中間使用半角逗號分隔,不能用* 通配符-->
<property name="basePackage" value="cn.lpj.dao"/>
<!-- 配置SqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!-- 5 事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--6 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 傳播行為 -->
<tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="search*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="*" propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config proxy-target-class="true">
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* cn.lpj.service.impl.*.*(..))"/>
</aop:config>
</beans>
5.springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 組件掃描 掃描所有標記@Controller類,由於使用自動掃描所以Controller類不用在spring配置文件中配置 -->
<context:component-scan base-package="cn.lpj.controller"/>
<!-- 處理器映射器和適配器,可以使用mvc注解驅動 -->
<mvc:annotation-driven/>
<!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 將jstl的jar包加入工程,默認支持jstl -->
<!-- 前綴和后綴可以去掉的,為了方便開發才加的 -->
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--進行靜態資源的訪問 -->
<mvc:resources location="/static/" mapping="/static/**"/>
<!-- 配置資源文件,防止被攔截 -->
<!-- <mvc:resources location="/WEB-INF/view/image/" mapping="/image/**"/>
<mvc:resources location="/WEB-INF/view/js/" mapping="/js/**"/>
<mvc:resources
location="/WEB-INF/view/css/" mapping="/css/**"/> -->
<!--攔截器-->
<mvc:interceptors>
<!--多個攔截器,順序執行-->
<!--登陸認證攔截器-->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="cn.lpj.interceptor.HandlerInterceptorAdapter"></bean>
</mvc:interceptor>
<!--<mvc:interceptor>-->
<!--<!– /**表示所有url包括子url路徑 –>-->
<!--<mvc:mapping path="/**"/>-->
<!--<bean class="cn.lpj.interceptor.HandlerInterceptorAdapter1"></bean>-->
<!--</mvc:interceptor>-->
</mvc:interceptors>
<!-- 攔截器 -->
<!--<mvc:interceptors>-->
<!--<bean-->
<!--class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">-->
<!--<property name="paramName" value="lang"></property>-->
<!--</bean>-->
<!--</mvc:interceptors>-->
<!--<mvc:interceptors>-->
<!--<mvc:interceptor>-->
<!--<mvc:mapping path="/*.do"/>-->
<!--<mvc:mapping path="/*.ajax"/>-->
<!--<mvc:mapping path="/*.jsp"/>-->
<!--<mvc:mapping path="/*.html"/>-->
<!--<!– 二級目錄 –>-->
<!--<mvc:mapping path="/*/*.do"/>-->
<!--<mvc:mapping path="/*/*.ajax"/>-->
<!--<mvc:mapping path="/*/*.jsp"/>-->
<!--<mvc:mapping path="/*/*.html"/>-->
<!--<!– 需排除攔截的地址 –>-->
<!--<mvc:exclude-mapping path="/login.jsp"/>-->
<!--<mvc:exclude-mapping path="/login.do"/>-->
<!--<mvc:exclude-mapping path="/getUserLoginInfo.do"/>-->
<!--<bean-->
<!--class="com.ouc.ulab.interceptor.UserSecurityInterceptor"></bean>-->
<!--</mvc:interceptor>-->
<!--</mvc:interceptors>-->
<!--<mvc:interceptors>-->
<!--<mvc:interceptor>-->
<!--<mvc:mapping path="/*.do"/>-->
<!--<mvc:mapping path="/*.ajax"/>-->
<!--<mvc:mapping path="/*.jsp"/>-->
<!--<mvc:mapping path="/*.html"/>-->
<!--<mvc:mapping path="/*/*.do"/>-->
<!--<mvc:mapping path="/*/*.ajax"/>-->
<!--<mvc:mapping path="/*/*.jsp"/>-->
<!--<mvc:mapping path="/*/*.html"/>-->
<!--<mvc:exclude-mapping path="/login.jsp"/>-->
<!--<mvc:exclude-mapping path="/login.do"/>-->
<!--<mvc:exclude-mapping path="/loadHome.do"/>-->
<!--<mvc:exclude-mapping path="/getUserLoginInfo.do"/>-->
<!--<bean-->
<!--class="com.ouc.ulab.interceptor.AuthoritySecurityInterceptor">-->
<!--</bean>-->
<!--</mvc:interceptor>-->
<!--</mvc:interceptors>-->
</beans>
7.
package cn.lpj.utils;
/**
* Created by Administrator on 2017/5/18.
*/
public class CustomerContextHolder {
public static final String DATA_SOURCE_170 = "dataSource-170";
public static final String DATA_SOURCE_236 = "dataSource-236";
public static final String DATA_SOURCE_225 = "dataSource-225";
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static void setCustomerType(String customerType) {
contextHolder.set(customerType);
}
public static String getCustomerType() {
return contextHolder.get();
}
// public static void clearCustomerType() {
// contextHolder.remove();
// }
public CustomerContextHolder() {
contextHolder.remove();
}
}
/**
* Created by Administrator on 2017/5/18.
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return CustomerContextHolder.getCustomerType();
}
}
package cn.lpj.interceptor;
import cn.lpj.utils.CustomerContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by Administrator on 2017/5/18.
*/
public class HandlerInterceptorAdapter implements HandlerInterceptor {
/**
* preHandle方法是進行處理器攔截用的,顧名思義,該方法將在Controller處理之前進
行調用,SpringMVC中的Interceptor攔截器是鏈式的,可以同時存在
* 多個Interceptor,然后SpringMVC會根據聲明的前后順序一個接一個的執行,而且所有
的Interceptor中的preHandle方法都會在
* Controller方法調用之前調用。SpringMVC的這種Interceptor鏈式結構也是可以進行中
斷的,這種中斷方式是令preHandle的返
* 回值為false,當preHandle的返回值為false的時候整個請求就結束了。
*/
// 在業務處理器處理請求之前被調用
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
CustomerContextHolder customerContextHolder = new CustomerContextHolder();
customerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_170);
System.out.println("-------------------------------------");
System.out.println("----------------我被執行了---------------------");
return true;
}
/**
* 這個方法只會在當前這個Interceptor的preHandle方法返回值為true的時候才會執行。
postHandle是進行處理器攔截用的,它的執行時間是在處理器進行處理之
* 后,也就是在Controller的方法調用之后執行,但是它會在DispatcherServlet進行視
圖的渲染之前執行,也就是說在這個方法中你可以對ModelAndView進行操
* 作。這個方法的鏈式結構跟正常訪問的方向是相反的,也就是說先聲明的Interceptor
攔截器該方法反而會后調用,這跟Struts2里面的攔截器的執行過程有點像,
* 只是Struts2里面的intercept方法中要手動的調用ActionInvocation的invoke方法,
Struts2中調用ActionInvocation的invoke方法就是調用下一個Interceptor
* 或者是調用action,然后要在Interceptor之前調用的內容都寫在調用invoke之前,要
在Interceptor之后調用的內容都寫在調用invoke方法之后。
*/
// 在業務處理器處理請求完成之后,生成視圖之前執行
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
System.out.println("----在Action方法執行完畢之后,執行(沒有拋異常的話)----------");
}
/**
* 該方法也是需要當前對應的Interceptor的preHandle方法的返回值為true時才會執行。
該方法將在整個請求完成之后,也就是DispatcherServlet渲染了視圖執行,
* 這個方法的主要作用是用於清理資源的,當然這個方法也只能在當前這個Interceptor
的preHandle方法的返回值為true時才會執行。
*/
// 在DispatcherServlet完全處理完請求之后被調用,可用於清理資源
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("----在Action 方法執行完畢之后,無論是否拋出異常,通常用來進行異常處理----------");
}
}
package cn.lpj.controller;
import cn.lpj.pojo.City;
import cn.lpj.service.CityService;
import cn.lpj.utils.CustomerContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by Administrator on 2017/5/4.
*/
@Controller
@RequestMapping(value = "/city")
public class CityController {
@Resource
private CityService cityService;
private final static Logger logger = LoggerFactory.getLogger(CityController.class);
@RequestMapping(value = "/searchCity")
public String searchCity(Model model) {
CustomerContextHolder customerContextHolder = new CustomerContextHolder();
customerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_170);
City city = new City();
city.setId(1);
List<City> cityList = cityService.searchCity(city);
System.out.println(cityList.get(0).getCity());
logger.info("logback 成功了--------------------------------------");
logger.error("logback 成功了");
model.addAttribute("cityList", cityList);
return "city/city";
}
}
/**
* Created by Administrator on 2017/5/4.
*/
@Controller
@RequestMapping(value = "/conf")
public class ConfController {
@Resource
private ConfService confService;
@RequestMapping(value = "/searchConf")
public String searchConf(Model model){
Conf conf = new Conf();
conf.setId(1);
List<Conf> list = confService.searchConf(conf);
model.addAttribute("list",list);
return "conf/conf";
}
}
/**
* Created by Administrator on 2017/5/5.
*/
@Controller
@RequestMapping(value = "/menu")
public class MenuController {
@Resource
private MenuService menuService;
@RequestMapping(value = "/searchMenu")
public String searchMenu(Model model) {
CustomerContextHolder customerContextHolder = new CustomerContextHolder();
customerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_236);
Menu menu = new Menu();
menu.setId(2);
List<Menu> list = menuService.searchMenu(menu);
System.out.println(list.get(0).getMenu());
return "menu/menu";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>simfence</display-name>
<!-- 1 加載spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/spring/applicationContext.xml,
classpath:/spring/applicationContext-*.xml
</param-value>
</context-param>
<!--Spring ApplicationContext 載入 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--2 springmvc的前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
<!--<url-pattern>/</url-pattern>-->
</servlet-mapping>
<!-- 解決post亂碼 -->
<!-- Character Encoding filter -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<!-- 連接池 啟用 Web 監控統計功能 start-->
<!--<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>-->
<!--<filter-mapping>-->
<!--<filter-name>DruidWebStatFilter</filter-name>-->
<!--<url-pattern>/*</url-pattern>-->
<!--</filter-mapping>-->
<!--<servlet>-->
<!--<servlet-name>DruidStatView</servlet-name>-->
<!--<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>-->
<!--</servlet>-->
<!--<servlet-mapping>-->
<!--<servlet-name>DruidStatView</servlet-name>-->
<!--<url-pattern>/druid/*</url-pattern>-->
<!--</servlet-mapping>-->
<servlet>
<servlet-name>DruidStatView</servlet-name>
<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DruidStatView</servlet-name>
<url-pattern>/druid/*</url-pattern>
</servlet-mapping>
<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>/public/*,*.js,*.css,/druid*,*.jsp,*.swf</param-value>
</init-param>
<init-param>
<param-name>principalSessionName</param-name>
<param-value>sessionInfo</param-value>
</init-param>
<init-param>
<param-name>profileEnable</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>druidWebStatFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 連接池 啟用 Web 監控統計功能 end-->
</web-app>
常見問題:

開始用的時候經常出現的問題,以為是密碼賬戶錯誤,后來檢查多遍,發現是在配置文件中多了幾個空格的原因;注意
