SSM和Spring Boot常用配置比较
一.Dao层相关
1.Mysql相关:
1.1配置DataSource连接池:
(1)SSM配置:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <!-- 加密后配置自己写的解析文件 --> 2 <bean class="com.swpu.o2o.util.EncryptPropertyPlaceholderConfigurer"> 3 <property name="locations"> 4 <list> 5 <!-- 需要解密的文件 --> 6 <value>classpath:jdbc.properties</value> 7 <value>classpath:redis.properties</value> 8 </list> 9 </property> 10 <!-- 设置编码为UTF-8 --> 11 <property name="fileEncoding" value="UTF-8"></property> 12 </bean>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource"> 2 <!-- 配置连接池属性 --> 3 <property name="driverClass" value="${jdbc.driver}" /> 4 <property name="jdbcUrl" value="${jdbc.url}" /> 5 <property name="user" value="${jdbc.username}" /> 6 <property name="password" value="${jdbc.password}" /> 7 <!-- c3p0连接池的私有属性 --> 8 <property name="maxPoolSize" value="30" /> 9 <property name="minPoolSize" value="10" /> 10 <!-- 关闭连接后不自动commit --> 11 <property name="autoCommitOnClose" value="false" /> 12 <!-- 获取连接超时时间 --> 13 <property name="checkoutTimeout" value="10000" /> 14 <!-- 当获取连接失败重试次数 --> 15 <property name="acquireRetryAttempts" value="2" /> 16 </bean>
(2)Spring Boot配置(写入Bean)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.swpu.o2o.config.dao; 2 3 import com.mchange.v2.c3p0.ComboPooledDataSource; 4 import com.swpu.o2o.util.DESUtils; 5 import org.mybatis.spring.annotation.MapperScan; 6 import org.springframework.beans.factory.annotation.Value; 7 import org.springframework.context.annotation.Bean; 8 import org.springframework.context.annotation.Configuration; 9 10 import java.beans.PropertyVetoException; 11 12 /** 13 * 配置dataSource到ioc容器里 14 */ 15 @Configuration 16 //配置mybatis mapper扫描路径 17 @MapperScan("com.swpu.o2o.dao") 18 public class DataSourceConfiguration { 19 //通过@Value标签获取application.properties中的配置信息 20 @Value("${jdbc.driver}") 21 private String jdbcDriver; 22 @Value("${jdbc.url}") 23 private String jdbcUrl; 24 @Value("${jdbc.username}") 25 private String jdbcUser; 26 @Value("${jdbc.password}") 27 private String jdbcPassword; 28 /** 29 * 生成与与spring-dao.xml对应的bean dataSource 30 */ 31 @Bean(name="dataSource") 32 public ComboPooledDataSource createDataSource() throws PropertyVetoException { 33 //生成dataSource实例 34 ComboPooledDataSource dataSource=new ComboPooledDataSource(); 35 //配置相关信息(和配置文件一样) 36 //驱动(强制异常处理,抛出去) 37 dataSource.setDriverClass(jdbcDriver); 38 //数据库连接url 39 dataSource.setJdbcUrl(jdbcUrl); 40 //用户名(解密) 41 dataSource.setUser(DESUtils.getDecryptString(jdbcUser)); 42 //密码 43 dataSource.setPassword(DESUtils.getDecryptString(jdbcPassword)); 44 return dataSource; 45 } 46 }
1.2创建SqlSessionFactoryBean实例(设置设置mybatis configuration扫描路径,mapper映射路径,配置扫描Dao接口包等)
(1)SSM配置:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <!-- 3.配置SqlSessionFactory对象 --> 2 <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory"> 3 <!-- 注入数据库连接池 --> 4 <property name="dataSource" ref="dataSource" /> 5 <!-- 配置MyBaties全局配置文件:mybatis-config.xml --> 6 <property name="configLocation" value="classpath:mybatis-config.xml" /> 7 <!-- 扫描entity包 使用别名 --> 8 <property name="typeAliasesPackage" value="com.swpu.o2o.entity" /> 9 <!-- 扫描sql配置文件:mapper需要的xml文件 --> 10 <property name="mapperLocations" value="classpath:mapper/*.xml" /> 11 </bean> 12 <!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 --> 13 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 14 <!-- 注入sqlSessionFactory --> 15 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> 16 17 <!-- 给出需要扫描Dao接口包 --> 18 <property name="basePackage" value="com.swpu.o2o.dao" /> 19 </bean>
(2)Spring Boot配置:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.swpu.o2o.config.dao; 2 3 import org.mybatis.spring.SqlSessionFactoryBean; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.beans.factory.annotation.Value; 6 import org.springframework.context.annotation.Bean; 7 import org.springframework.context.annotation.Configuration; 8 import org.springframework.core.io.ClassPathResource; 9 import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 10 import org.springframework.core.io.support.ResourcePatternResolver; 11 12 import javax.sql.DataSource; 13 import java.io.IOException; 14 15 @Configuration 16 public class SessionFactoryConfiguration { 17 //mybatis-config.xml配置文件路径 18 //注意:静态(static)的变量不能直接通过@Value获取,可以通过set方法 19 private static String mybatisConfigFile; 20 //mybatis mapper文件所在路径 21 private static String mapperPath; 22 23 @Value("${mybatis_config_file}") 24 public void setMybatisConfigFile(String mybatisConfigFile) { 25 SessionFactoryConfiguration.mybatisConfigFile = mybatisConfigFile; 26 } 27 28 @Value("${mapper_path}") 29 public void setMapperPath(String mapperPath) { 30 SessionFactoryConfiguration.mapperPath = mapperPath; 31 } 32 33 //实体类所在package 34 @Value("${type_alias_package}") 35 private String typeAliasPackage; 36 @Autowired 37 private DataSource dataSource; 38 /** 39 * 创建SqlSessionFactoryBean实例,并且设置mapper映射路径 40 * 设置dataSource数据源 41 */ 42 @Bean(name = "sqlSessionFactory") 43 public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException { 44 SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); 45 //设置mybatis configuration扫描路径 46 sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFile)); 47 //设置mapper 扫描路径 48 PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver(); 49 String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath; 50 sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath)); 51 //设置dataSource 52 sqlSessionFactoryBean.setDataSource(dataSource); 53 //设置typeAlias包扫描路径 54 sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasPackage); 55 return sqlSessionFactoryBean; 56 } 57 }
(3)Mybatis配置文件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 <!-- 配置全局属性 --> 7 <settings> 8 <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 --> 9 <setting value="true" name="useGeneratedKeys" /> 10 <!-- 使用列别名替换列名 默认:true --> 11 <setting value="true" name="useColumnLabel" /> 12 <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} --> 13 <setting value="true" name="mapUnderscoreToCamelCase" /> 14 <!-- 打印查询语句 --> 15 </settings> 16 17 </configuration>
2.Redis:
(1)SSM配置:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <beans xmlns="http://www.springframework.org/schema/beans" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 3 xsi:schemaLocation="http://www.springframework.org/schema/beans 4 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 5 http://www.springframework.org/schema/context 6 http://www.springframework.org/schema/context/spring-context-3.2.xsd"> 7 <!-- Redis连接池配置 --> 8 <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> 9 <!-- 控制一个pool能分配多少个jedis实例 --> 10 <property name="maxTotal" value="${redis.pool.maxActive}" /> 11 <!-- 连接池中最多空闲多少个maxIdle个连接,这里为20,表示即使没有数据库连接时依然可以保持20空闲的连接,而不被清除,处于待命状态,随时连接 --> 12 <property name="maxIdle" value="${redis.pool.maxIdle}" /> 13 <!-- 最大等待时间,当没有可用连接时,连接池等待连接被归还的最大时间(以毫秒计数),超过时间即抛出异常 --> 14 <property name="maxWaitMillis" value="${redis.pool.maxWait}" /> 15 <!-- 在获取连接时,检查有效性 --> 16 <property name="testOnBorrow" value="${redis.pool.testOnBorrow}" /> 17 </bean> 18 <!-- 创建Redis连接池,并做相关配置 --> 19 <bean id="jedisWritePool" class="com.swpu.o2o.cache.JedisPoolWriper" 20 depends-on="jedisPoolConfig"> 21 <constructor-arg index="0" ref="jedisPoolConfig" /> 22 <constructor-arg index="1" value="${redis.hostname}" /> 23 <constructor-arg index="2" value="${redis.port}" type="int" /> 24 </bean> 25 <!-- 创建Redis工具类,封装好Redis的连接以进行相关操作 --> 26 <bean id="jedisUtil" class="com.swpu.o2o.cache.JedisUtil" 27 scope="singleton"> 28 <property name="jedisPool"> 29 <ref bean="jedisWritePool" /> 30 </property> 31 </bean> 32 <bean id="jedisKeys" class="com.swpu.o2o.cache.JedisUtil$Keys" 33 scope="singleton"> 34 <constructor-arg ref="jedisUtil"></constructor-arg> 35 </bean> 36 <bean id="jedisStrings" class="com.swpu.o2o.cache.JedisUtil$Strings" 37 scope="singleton"> 38 <constructor-arg ref="jedisUtil"></constructor-arg> 39 </bean> 40 <bean id="jedisLists" class="com.swpu.o2o.cache.JedisUtil$Lists" 41 scope="singleton"> 42 <constructor-arg ref="jedisUtil"></constructor-arg> 43 </bean> 44 <bean id="jedisSets" class="com.swpu.o2o.cache.JedisUtil$Sets" 45 scope="singleton"> 46 <constructor-arg ref="jedisUtil"></constructor-arg> 47 </bean> 48 <bean id="jedisHash" class="com.swpu.o2o.cache.JedisUtil$Hash" 49 scope="singleton"> 50 <constructor-arg ref="jedisUtil"></constructor-arg> 51 </bean> 52 53 </beans>
(2)Spring Boot配置:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.swpu.o2o.config.redis; 2 3 import com.swpu.o2o.cache.JedisPoolWriper; 4 import com.swpu.o2o.cache.JedisUtil; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.beans.factory.annotation.Value; 7 import org.springframework.context.annotation.Bean; 8 import org.springframework.context.annotation.Configuration; 9 import redis.clients.jedis.JedisPoolConfig; 10 11 /** 12 * 对应spring-redis.xml里的配置 13 */ 14 @Configuration 15 public class RedisConfiguration { 16 @Value("${redis.hostname}") 17 private String hostName; 18 @Value("${redis.port}") 19 private int port; 20 @Value("${redis.pool.maxActive}") 21 private int maxTotal; 22 @Value("${redis.pool.maxIdle}") 23 private int maxIdle; 24 @Value("${redis.pool.maxWait}") 25 private long maxWaitMillis; 26 @Value("${redis.pool.testOnBorrow}") 27 private boolean testOnBrrow; 28 29 @Autowired 30 private JedisPoolConfig jedisPoolConfig; 31 @Autowired 32 private JedisPoolWriper jedisWritePool; 33 @Autowired 34 private JedisUtil jedisUtil; 35 36 /** 37 * 创建redis连接池设置 38 */ 39 @Bean(name = "jedisPoolConfig") 40 public JedisPoolConfig createJedisPoolConfig() { 41 JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); 42 //控制一个pool可分配给多个jedis实例 43 jedisPoolConfig.setMaxTotal(maxTotal); 44 //连接池中最多空闲maxIdle个连接,这里取值20 45 //表示即使没有数据库连接时依然可以保持20空闲的连接,而不清除,随时处于待命的状态 46 jedisPoolConfig.setMaxIdle(maxIdle); 47 //最大等待时间:当没有可用连接时 48 //连接池等待连接被归还的最大时间(以毫秒计数),超过时间则抛出异常 49 jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); 50 //在获取连接的时候检查有效性 51 jedisPoolConfig.setTestOnBorrow(testOnBrrow); 52 return jedisPoolConfig; 53 } 54 55 /** 56 * 创建Redis连接池,并做相关配置 57 */ 58 @Bean(name = "jedisWritePool") 59 public JedisPoolWriper createJedisPoolWripper() { 60 JedisPoolWriper jedisWritePool = new JedisPoolWriper(jedisPoolConfig, hostName, port); 61 return jedisWritePool; 62 } 63 64 /** 65 * 创建Redis工具类,封装好Redis的连接以进行相关的操作 66 */ 67 @Bean(name = "jedisUtil") 68 public JedisUtil createJedisUtil() { 69 JedisUtil jedisUtil = new JedisUtil(); 70 jedisUtil.setJedisPool(jedisWritePool); 71 return jedisUtil; 72 } 73 74 /** 75 * Redis的key操作 76 */ 77 @Bean(name = "jedisKeys") 78 public JedisUtil.Keys createJedisKeys() { 79 //实例化内部类 80 JedisUtil.Keys jedisKeys = jedisUtil.new Keys(); 81 return jedisKeys; 82 } 83 84 /** 85 * Redis的String操作 86 */ 87 @Bean(name = "jedisStrings") 88 public JedisUtil.Strings createJedisStrings() { 89 //实例化内部类 90 JedisUtil.Strings jedisStrings = jedisUtil.new Strings(); 91 return jedisStrings; 92 } 93 94 /** 95 * Redis的List操作 96 */ 97 @Bean(name = "jedisLists") 98 public JedisUtil.Lists createJedisLists() { 99 //实例化内部类 100 JedisUtil.Lists jedisLists = jedisUtil.new Lists(); 101 return jedisLists; 102 } 103 104 /** 105 * Redis的Hash操作 106 */ 107 @Bean(name = "jedisHash") 108 public JedisUtil.Hash createJedisHash() { 109 //实例化内部类 110 JedisUtil.Hash jedisHash = jedisUtil.new Hash(); 111 return jedisHash; 112 } 113 114 /** 115 * Redis的sets操作 116 */ 117 @Bean(name = "jedisSets") 118 public JedisUtil.Sets createJedisSets() { 119 //实例化内部类 120 JedisUtil.Sets jedisSets = jedisUtil.new Sets(); 121 return jedisSets; 122 } 123 124 125 126 }
JedisPool类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.swpu.o2o.cache; 2 3 import redis.clients.jedis.JedisPool; 4 import redis.clients.jedis.JedisPoolConfig; 5 6 /** 7 * 强指定redis的JedisPool接口构造函数,这样才能在centos成功创建jedispool 8 * 9 * @author xiangze 10 * 11 */ 12 public class JedisPoolWriper { 13 //连接池对象 14 private JedisPool jedisPool; 15 16 public JedisPoolWriper(final JedisPoolConfig poolConfig, final String host, 17 final int port) { 18 try { 19 //通过连接池配置信息,IP,端口构造连接池对象 20 jedisPool = new JedisPool(poolConfig, host, port); 21 } catch (Exception e) { 22 e.printStackTrace(); 23 } 24 } 25 //获取redis连接池对象 26 public JedisPool getJedisPool() { 27 return jedisPool; 28 } 29 //注入redis连接池对象 30 public void setJedisPool(JedisPool jedisPool) { 31 this.jedisPool = jedisPool; 32 } 33 34 }
二.Service层相关(配置事务管理器,声明式事务)
(1)SSM配置:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context.xsd 10 http://www.springframework.org/schema/tx 11 http://www.springframework.org/schema/tx/spring-tx.xsd"> 12 <!-- 扫描service包下所有使用注解的类型 --> 13 <context:component-scan base-package="com.swpu.o2o.service" /> 14 15 <!-- 配置事务管理器 --> 16 <bean id="transactionManager" 17 class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 18 <!-- 注入数据库连接池 --> 19 <property name="dataSource" ref="dataSource" /> 20 </bean> 21 22 <!-- 配置基于注解的声明式事务 --> 23 <tx:annotation-driven transaction-manager="transactionManager" /> 24 </beans>
(2)Spring Boot配置:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.swpu.o2o.config.service; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.context.annotation.Configuration; 5 import org.springframework.jdbc.datasource.DataSourceTransactionManager; 6 import org.springframework.transaction.PlatformTransactionManager; 7 import org.springframework.transaction.annotation.EnableTransactionManagement; 8 import org.springframework.transaction.annotation.TransactionManagementConfigurer; 9 10 import javax.sql.DataSource; 11 12 /** 13 * 对应spring-service.xml里面的transactionManager 14 * 继承transactionManagementConfigurer:不能直接加入Bean,因为开启了annotation-driven 15 */ 16 @Configuration 17 //首先使用注解@EnableTransactionManagement开启事务后 18 //在Service方法上添加注解@Transactional 19 @EnableTransactionManagement 20 public class TransactionManageConfiguration implements TransactionManagementConfigurer { 21 @Autowired 22 //注入DataSourceConfiguration里面的dataSource,通过createDataSource()获取 23 private DataSource dataSource; 24 25 @Override 26 /** 27 * 关于事务处理,需要返回PlatformTransactionManager的实现 28 */ 29 public PlatformTransactionManager annotationDrivenTransactionManager() { 30 return new DataSourceTransactionManager(dataSource); 31 } 32 }
三.Controller层相关
配置SpringMVC:
1.开启SpringMVC注解模式;2.静态资源默认servlet配置;3.定义视图解析器;4.扫描web相关的bean;5.权限拦截器
(1)SSM配置:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:mvc="http://www.springframework.org/schema/mvc" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context.xsd 9 http://www.springframework.org/schema/mvc 10 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> 11 <!-- 配置SpringMVC --> 12 <!-- 1.开启SpringMVC注解模式 --> 13 <!-- 简化配置: (1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter 14 (2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持 --> 15 <mvc:annotation-driven /> 16 17 <!-- 2.静态资源默认servlet配置 (1)加入对静态资源的处理:js,gif,png (2)允许使用"/"做整体映射 --> 18 <mvc:resources mapping="/resources/**" location="/resources/" /> 19 <mvc:default-servlet-handler /> 20 21 <!-- 3.定义视图解析器 --> 22 <!-- 定制请求加头加尾 --> 23 <bean id="viewResolver" 24 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 25 <property name="prefix" value="/WEB-INF/html/"></property> 26 <property name="suffix" value=".html"></property> 27 </bean> 28 <bean id="multipartResolver" 29 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 30 <!-- 默认编码 --> 31 <property name="defaultEncoding" value="utf-8"></property> 32 <!-- 上传文件的最大 尺寸(单位是字节) --> 33 <!-- 1024*1024*20=20971520 --> 34 <property name="maxUploadSize" value="20971520"></property> 35 <!-- 允许写在内存中的最大值 --> 36 <property name="maxInMemorySize" value="20971520"></property> 37 </bean> 38 <!-- 4.扫描web相关的bean --> 39 <context:component-scan base-package="com.swpu.o2o.web" /> 40 <!-- 5.权限拦截器 --> 41 <mvc:interceptors> 42 <!-- 校验是否登录了该管理系统的拦截器 --> 43 <mvc:interceptor> 44 <!-- 定义拦截的路由,shopadmin包下的所有Controller --> 45 <mvc:mapping path="/shopadmin/**" /> 46 <!-- 拦截方法 --> 47 <bean class="com.swpu.o2o.interceptor.shopadmin.ShopLoginInterceptor" 48 id="ShopInterceptor" /> 49 </mvc:interceptor> 50 <!-- 校验是否对该店铺有操作权限的拦截器 --> 51 <mvc:interceptor> 52 <!-- 需要拦截的接口 --> 53 <mvc:mapping path="/shopadmin/**" /> 54 <!-- shoplist page --> 55 <!-- 排除该包下的某些接口不拦截 --> 56 <mvc:exclude-mapping path="/shopadmin/shoplist" /> 57 <mvc:exclude-mapping path="/shopadmin/getshoplist" /> 58 <!-- shopmanage page --> 59 <mvc:exclude-mapping path="/shopadmin/shopmanagement" /> 60 <mvc:exclude-mapping path="/shopadmin/getshopmanagementinfo" /> 61 <!-- shopregister page --> 62 <mvc:exclude-mapping path="/shopadmin/getshopinitinfo" /> 63 <mvc:exclude-mapping path="/shopadmin/shopoperation" /> 64 <mvc:exclude-mapping path="/shop/registershop" /> 65 <bean class="com.swpu.o2o.interceptor.shopadmin.ShopPermissionInterceptor" 66 id="ShopPermissionInterceptor" /> 67 </mvc:interceptor> 68 </mvc:interceptors> 69 </beans>
(2)Spring Boot配置:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.swpu.o2o.config.web; 2 3 import com.google.code.kaptcha.servlet.KaptchaServlet; 4 import com.swpu.o2o.interceptor.ShopLoginInterceptor; 5 import com.swpu.o2o.interceptor.ShopPermissionInterceptor; 6 import org.springframework.beans.BeansException; 7 import org.springframework.beans.factory.annotation.Value; 8 import org.springframework.boot.web.servlet.ServletRegistrationBean; 9 import org.springframework.context.ApplicationContext; 10 import org.springframework.context.ApplicationContextAware; 11 import org.springframework.context.annotation.Bean; 12 import org.springframework.context.annotation.Configuration; 13 import org.springframework.web.multipart.commons.CommonsMultipartResolver; 14 import org.springframework.web.servlet.ViewResolver; 15 import org.springframework.web.servlet.config.annotation.*; 16 import org.springframework.web.servlet.view.InternalResourceViewResolver; 17 18 import javax.servlet.ServletException; 19 20 /** 21 * 开启Mvc,自动注入spring容器中 22 * WebMvcConfigurer:配置视图解析器 23 * 当一个类实现了接口WebMvcConfigurer,这个类就能方便的获取里面所有的bean 24 */ 25 @Configuration 26 //等价于<mvc:annotation-driven/>,使用Java 注解快捷配置Spring Webmvc 27 @EnableWebMvc 28 //实现ApplicationContextAware该接口获取Spring容器 29 // extends WebMvcConfigurationSupport implements ApplicationContextAware 30 public class MvcConfiguration extends WebMvcConfigurerAdapter implements ApplicationContextAware { 31 //Spring容器 32 private ApplicationContext applicationContext; 33 34 @Override 35 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 36 this.applicationContext = applicationContext; 37 } 38 39 /** 40 * 静态资源配置(docBase) 41 * 42 * 43 * @param registry 44 */ 45 @Override 46 public void addResourceHandlers(ResourceHandlerRegistry registry) { 47 //拦截/resources下的请求解析到目标路径classpath:/resources 48 //classpath表示在项目工程中找,file表示在服务器中找 49 registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/Project/image/upload/"); 50 } 51 52 /** 53 * 定义默认的请求处理器 54 * 55 * @param configurer 56 */ 57 @Override 58 public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 59 configurer.enable(); 60 } 61 62 /** 63 * 创建viewResolver 64 * @return 65 */ 66 @Bean(name = "viewResolver") 67 public ViewResolver createViewResolver() { 68 InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); 69 //设置spring容器 70 //viewResolver.setApplicationContext(this.applicationContext); 71 //取消缓存 72 viewResolver.setCache(false); 73 //设置解析的前缀 74 viewResolver.setPrefix("/WEB-INF/html/"); 75 //设置视图解析的后缀 76 viewResolver.setSuffix(".html"); 77 return viewResolver; 78 } 79 80 /** 81 * 文件上传解析器 82 * 83 * @return 84 */ 85 @Bean(name = "multipartResolver") 86 public CommonsMultipartResolver commonsMultipartResolver() { 87 CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); 88 multipartResolver.setDefaultEncoding("utf-8"); 89 //文件大小1024*1024*20 90 multipartResolver.setMaxUploadSize(20971520); 91 multipartResolver.setMaxInMemorySize(20971520); 92 return multipartResolver; 93 } 94 //引入验证码kaptcha相关信息 95 @Value("${kaptcha.border}") 96 private String border; 97 @Value("${kaptcha.textproducer.font.color}") 98 private String fcolor; 99 @Value("${kaptcha.image.width}") 100 private String width; 101 @Value("${kaptcha.textProducer.char.string}") 102 private String cString; 103 @Value("${kaptcha.image.height}") 104 private String height; 105 @Value("${kaptcha.textproducer.font.size}") 106 private String fsize; 107 @Value("${kaptcha.noise.color}") 108 private String nColor; 109 @Value("${kaptcha.textproducer.char.length}") 110 private String clength; 111 @Value("${kaptcha.textproducer.font.names}") 112 private String fnames; 113 114 /** 115 * web.xml不生效了,在这里配置Kaptcha验证码Servlet 116 * @return 117 */ 118 @Bean 119 public ServletRegistrationBean servletRegistrationBean() throws ServletException { 120 ServletRegistrationBean servlet=new ServletRegistrationBean(new KaptchaServlet(),"/Kaptcha"); 121 servlet.addInitParameter("kaptcha.border",border);//无边框 122 servlet.addInitParameter("kaptcha.textproducer.font.color",fcolor);//字体颜色 123 servlet.addInitParameter("kaptcha.image.width",width);//图片宽度 124 servlet.addInitParameter("kaptcha.textProducer.char.string",cString);//使用哪些字体 125 servlet.addInitParameter("kaptcha.image.height",height);//图片高度 126 servlet.addInitParameter("kaptcha.textproducer.font.size",fsize);//字体大小 127 servlet.addInitParameter("kaptcha.noise.color",nColor);//干扰线颜色 128 servlet.addInitParameter("kaptcha.textproducer.char.length",clength);//字符个数 129 servlet.addInitParameter("kaptcha.textproducer.font.names",fnames);//字体 130 return servlet; 131 132 } 133 134 /** 135 * 拦截器 136 * @param registry 137 */ 138 @Override 139 public void addInterceptors(InterceptorRegistry registry) { 140 String interceptPath="/shopadmin/**"; 141 //注册拦截器(验证是否登录) 142 InterceptorRegistration loginIR=registry.addInterceptor(new ShopLoginInterceptor()); 143 //配置拦截器路径 144 loginIR.addPathPatterns(interceptPath); 145 //注册拦截器(验证是否具有权限) 146 InterceptorRegistration permissionIR=registry.addInterceptor(new ShopPermissionInterceptor()); 147 //配置拦截器路径 148 permissionIR.addPathPatterns(interceptPath); 149 //配置不拦截的路径 150 permissionIR.excludePathPatterns("/shopadmin/shoplist"); 151 permissionIR.excludePathPatterns("/shopadmin/getshoplist"); 152 permissionIR.excludePathPatterns("/shopadmin/registershop"); 153 permissionIR.excludePathPatterns("/shopadmin/shopoperation"); 154 permissionIR.excludePathPatterns("/shopadmin/shopmanagement"); 155 permissionIR.excludePathPatterns("/shopadmin/getshopmanagementinfo"); 156 } 157 }
注:WebMvcConfigurerAdapter在Spring Boot2.0就已经过时,不推荐使用,可以继承WebMvcConfigurationSupport。该类包含了WebMvcConfigurerAdapter的所有方法。