参考博客: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>
常见问题:
开始用的时候经常出现的问题,以为是密码账户错误,后来检查多遍,发现是在配置文件中多了几个空格的原因;注意